self keyword refers to the current instance of the class that a block of code belongs to. It provides access to the members of the class (although by default they are in scope without the need for a
self, and also makes the current instance available, for exa ple to be passed or assigned to other places.
type Foo = public class private property Value: String; public method Test; begin var x := Value; // members can be access directly... var u := self.Value; // ... but also via `self`; var f: Foo := self; // `self` represents the instance as a whole. end; end;
As discussed in Member Access Expressions,
self can be helpful to avoid ambiguity, or access class members that are "hidden" from by another identifier of the same name. It can also provide clarity and code improve readability, in places where it might not be obvious which identifiers refer to type members, and which don't:
method UpdateValue(Value: String); begin self.Value := Value; // the paramer hides the property end;
Self in Static Members
static members (defined with the
static modifier or the
class var or
class event prefix),
self refers to the (platform-specific) meta-class that describes the current type. This can be assumed to be unique for each type, and distinct for separate types, and allows for polymorphism (i.e. in descendant class,
self will refer to the descendant meta-class:
self inside a static member is identical to
(self) in an instance method.