Name

Self Variable

Syntax

var Self: Class type;

Description

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.

Tips and Tricks

  • 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.

Example

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;

See Also

CDecl Directive, Class Keyword, Pascal Directive, Register Directive, Safecall Directive, StdCall Directive, TObject Type
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset