LoginSignup
2
1

More than 5 years have passed since last update.

Self 4変化

Last updated at Posted at 2017-04-24

Self

多くのオブジェクト指向言語が、メソッド内で自分自身のインスタンスを表すために特別な単語を使います。
C++ を始めとした多くの C系言語では this でしょう。
同様に Object Pascal にも当然、自分自身を表す特別な単語があります。
それが Self です。

Self はコンテキスト依存

C系の言語が用いる this は、本当に「自分自身のインスタンスを表す」だけですが、Object Pascal の Self はコンテキストで意味が変わってきます。
以下、4つほど Self の機能を紹介します。

1.自分自身のインスタンスを表す

ごく一般的な意味の Self です。
いわゆる this です。

type
  TFoo = class
  public
    procedure Bar;
  end;

procedure TFoo.Bar;
begin
  // 自分自身のインスタンスのクラス名を表示
  Writeln(Self.ClassName);
end;

2.メタクラスを表す

クラスメソッド(他の言語でいう静的メソッド。Delphi では static メソッドも存在するので厳密には違う意味です)でも Self が使えます。
多くの C系言語では静的メソッドで this は使えないと思います。

この時の Self はクラス参照(メタクラス)を返します。

type
  TFoo = class
  public
    class procedure Bar;
  end;

class procedure TFoo.Bar;
begin
  // クラス参照型からクラス名を取得して表示
  Writeln(Self.ClassName);
end;

3.対象クラスのインスタンスを表す

class helper という機能を使うと、対象のクラスを機能拡張できます。
この時の Self は元々のクラスのメソッドと同様に対象クラスのインスタンスを返します。

type
  TFoo = class
  public
  end;

  // TFoo に Baz というメソッドを追加する TBar というクラスヘルパー
  TBar = class helper for TFoo
  public
    procedure Baz;
  end;

procedure TBar.Baz;
begin
  // この Self は TFoo 型のインスタンス
  Writeln(Self.ClassName);
end;

4.プリミティブ型の値を表す

record helper という機能を使うと、整数型などのプリミティブ型をあたかもクラスのように機能拡張できます。

この時の Self はプリミティブ型の値そのものを返します。

type
  // ShortInt型を拡張する
  TFoo = record helper for ShortInt
  public
    procedure Bar;
  end;

procedure TFoo.Bar;
begin
  // このときの Self は ShortInt型の値
  Writeln(Self);
end;

begin
  // こんな風にプリミティブ型があたかもクラスのように呼び出せる
  // このとき Bar 内の Self は 0 が入っている
  0.Bar; 
end.

まとめ

Self を軸としてまとめた文書が見当たらなかったので書いてみました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1