Class method



Class method
Pas2JS pascal source code
type TMyClass = class class procedure WriteLnMyName; class function GetMyName : String; virtual; end; type TMyOtherClass = class (TMyClass) class procedure WriteLnMyName; class function GetMyName : String; override; end; class procedure TMyClass.WriteLnMyName; begin WriteLn('TMyClass'); end; class function TMyClass.GetMyName : String; begin Result:='This is TMyClass'; end; class procedure TMyOtherClass.WriteLnMyName; begin WriteLn('TMyOtherClass'); end; class function TMyOtherClass.GetMyName : String; begin Result:='I''m TMyOtherClass'; end; { TEST II } type TClassB = class class procedure ClassProc; method DoIt; end; class procedure TClassB.ClassProc; begin WriteLn(ClassName+' ClassProc'); end; method TClassB.DoIt; begin ClassProc; Self.ClassProc; end; { TEST III } type TBase = class class method Test; virtual; class method Test2; class method CallVirtual; virtual; class method Call; end; type TChild = class(TBase) class method CallVirtual; override; end; class method TBase.Test; begin WriteLn('test '+ClassName); end; class method TBase.Test2; begin WriteLn('test2 '+ClassName); end; class method TBase.CallVirtual; begin Test; Test2; end; class method TBase.Call; begin Test; Test2; end; class method TChild.CallVirtual; begin WriteLn('overridden'); inherited CallVirtual; end; { unit1.pas } var my : TMyClass; myo : TMyOtherClass; b := TClassB.Create; c : TChild := new TChild; d : TClass := TObject.ClassType; Begin TMyClass.WriteLnMyName; TMyOtherClass.WriteLnMyName; WriteLn(TMyClass.GetMyName); WriteLn(TMyOtherClass.GetMyName); my:=TMyClass.Create; my.WriteLnMyName; WriteLn(my.GetMyName); my:=TMyOtherClass.Create; my.WriteLnMyName; WriteLn(my.GetMyName); myo:=TMyOtherClass.Create; myo.WriteLnMyName; WriteLn(myo.GetMyName); myo:=nil; try myo.WriteLnMyName; except on E: Exception do WriteLn(e.Message); end; { ### CONSOLE OUTPUTS ### TMyClass TMyOtherClass This is TMyClass I'm TMyOtherClass TMyClass This is TMyClass TMyClass I'm TMyOtherClass TMyOtherClass I'm TMyOtherClass TypeError, Cannot read property 'ClassType' of null } { TEST II } b.ClassProc; TClassB.ClassProc; b.DoIt; { ### CONSOLE OUTPUTS ### TClassB ClassProc TClassB ClassProc TClassB ClassProc TClassB ClassProc } { TEST III } c.Test; TChild.Test; c.Test2; TChild.Test2; c.Call; c.CallVirtual; TChild.Call; TChild.CallVirtual; { ### CONSOLE OUTPUTS ### test TChild test TChild test2 TChild test2 TChild test TChild test2 TChild overridden test TChild test2 TChild test TChild test2 TChild overridden test TChild test2 TChild } { TEST IV } WriteLn(TClass.ClassName); WriteLn(TClass.ClassType.ClassName); WriteLn(d.ClassName); WriteLn(d.ClassType.ClassName); { ### CONSOLE OUTPUTS ### TObject TObject TObject TObject }