Function Pointer



A function can be called via a function pointer to access a global variable for instance.
Pas2JS pascal source code
{ filename: A.pas } unit A; interface uses SmartCL.System; type TFooObject = class private FValue: Integer; public constructor Create(A: Integer); function Value: Integer; end; var AFoo: TFooObject; implementation constructor TFooObject.Create(A: Integer); begin FValue := A; end; function TFooObject.Value: Integer; begin Result := FValue; end; end. { filename: uMain.pas } type TSettingFunction = function(): Boolean; function Foo: TFooObject; begin if AFoo = nil then AFoo := TFooObject.Create(42); Result := AFoo; end; function Setting(): Boolean; begin WriteLn(IntToStr(Foo.Value)); Result := True; end; { TApplication } procedure TApplication.RunApp; var SettingFunction: TSettingFunction = Setting; begin SettingFunction(); // result is: 42 end;