Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`this` keyword equivalent in delphi [duplicate]

Let's say that we have this class:

unit Traitement;

interface

type
  TTraitement =class
  public        
    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 I used to be a Java programmer, and in this case I would use the keyword this. Does Pascal have an equivalent for the this keyword? If not, how can I achieve this kind of call?

like image 490
Billydan Avatar asked Jan 05 '23 08:01

Billydan


1 Answers

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.

like image 112
David Heffernan Avatar answered Jan 11 '23 08:01

David Heffernan