`this` keyword equivalent in delphi [duplicate]
Asked Answered
S

1

5

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?

Selangor answered 21/9, 2016 at 13:17 Comment(2)
FWIW: You can just call it like func1(...); - no need for qualifying it with Self.Karlenekarlens
Note that Self in Object Pascal isn't really a keyword, but rather an implicit variable.Mather
M
10

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.

Morelos answered 21/9, 2016 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.