Billydan Billydan - 2 months ago 14
Pascal Question

`this` keyword equivalent in delphi

let's say that we have this class

unit Traitement;

interface

type
TTraitement =class
public
constructor Create();
destructor Destroy;override;
function func1(param:String): String;
function func2(param:String): String;
end;

implementation

function TTraitement.func1(param:String): String;
begin
//some code
end;

function TTraitement.func2(param:String): String;
begin
//some code
end;

end.


And I want to call
func1
in the code of
func2
. Well Iused to be a java programmer and in this case i would use the keyword
this
. I wonder if pascal has an equivalent for this keyword, and if not how can I achieve this kind of call?

Answer

The equivalent to Java's this in Delphi is Self. From the documentation:

Self

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 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' methods. In this case, you can access the original member identifier as Self.Identifier.

Note, however, that the example code in the question has no need to use Self. In that code you can call func1 from func2 omitting Self.

The example given in the above documentation excerpt does provide proper motivation for the existence of Self.