Self Variable
In every
method, Delphi declares the Self
variable as a
hidden parameter. In a method, the value of the
Self
variable is the object reference. In a class
method, Self
is the class reference.
A constructor can assign a new value to Self
,
which becomes the value the constructor returns. Usually, though, you
should override the NewInstance
method instead of
assigning to Self
.
In ordinary methods, assigning to Self
has no
effect outside the method.
A method also has an implicit with
Self
do
for the method’s
body. In other words, all of the fields, methods, and properties are
in scope, and you can refer to them without the explicit reference to
Self
.
In the register
calling convention,
Self
is the first argument, so it is passed in the
EAX
register.
In the pascal
calling convention,
Self
is the last argument, so it is pushed last
onto the stack, after all other arguments.
In the cdecl
, safecall
, and
stdcall
calling conventions,
Self
is the last argument to a procedure, so it is
pushed first onto the stack. If a function must return a string,
dynamic array, Variant
or large record result, a
pointer to the result is pushed after Self
, as a
hidden var
parameter.
procedure TForm1.FormCreate(Sender: TObject); var Button: TButton; begin Button := TButton.Create(Self); Button.Parent := Self; // Center the button on the form. Note that Self.ClientWidth // and plain ClientWidth are the same property. Button.Left := (Self.ClientWidth - Button.Width) div 2; Button.Top := (ClientHeight - Button.Height) div 2; Button.Caption := 'Click me!'; Button.OnClick := ButtonClick; // or use Self.ButtonClick end;