Within
the implementation of a method, the identifier Self references the
object in which the method is called. For example, here is the implementation
of TCollection’s Add method in the Classes unit.
function
TCollection.Add: TCollectionItem;
begin
Result := FItemClass.Create(Self);
end;
The Add
method calls the Create method in the class referenced by the FItemClass
field, which is always a TCollectionItem descendant. TCollectionItem.Create
takes a single parameter of type TCollection, so Add passes it
the TCollection instance object where Add is called. This is
illustrated in the following code.
var
MyCollection: TCollection;
...
MyCollection.Add // MyCollection is passed to the
TCollectionItem.Create method
Self is useful for a variety of reasons. For example, a member
identifier declared in a class type might be redeclared in the block of one of
the class’s methods. In this case, you can access the original member
identifier as Self.Identifier.
For information about Self in class methods, see Class methods.
Method declarations
and implementations
在方法实现中,标识符Self引用方法调用所在的对象。例如,下面是Classes单元中TCollection类的Add方法的实现:
function
TCollection.Add: TCollectionItem;
begin
Result := FItemClass.Create(Self);
end;
这里,Add方法调用了由FItemClass域引用的类中的Create方法,它总是产生一个TCollectionItem后裔。TCollectionItem.Create接受了类型为TCollection的单个参数,因此当Add方法被调用时,Add方法将把TCollection的实例传递给TCollectionItem.Create方法。例如:
var
MyCollection: TCollection;
...
MyCollection.Add // MyCollection被传递到TCollectionItem.Create方法
有很多理由可以证明Self是有用的。例如,类类型中声明的成员标识符可能在类的方法的某个块中被再声明。这时,可以通过如Self.Identifier的形式实现对原始成员标识符的访问。
类方法中有关Self的更多信息(如该标识符在类方法中表示类而不是表示实例对象),见类方法。