[Pas2js] Interface implementation idea
warleyalex
warleyalex at yahoo.com.br
Thu Jan 18 03:25:48 CET 2018
> Is this mail meant as an inspiration for other users, or is this a
> proposal how pas2js could implement interfaces eventually?
This is a proposal.
Another proposal, would be inject an interface instance implemented in
delphi/fpc, f.i.:
-------------------------------------
unit Unit1;
interface
type
IMyInterface = interface
procedure SetValue(const Value: string);
function GetValue: string;
property Value: string read GetValue write SetValue;
procedure DoSomething;
end;
type
TMyClass = class(TObject)
private
FValue: String;
protected
procedure SetValue(const Value: string);
function GetValue: string;
public
property Value: string read FValue write FValue;
procedure DoSomething;
end;
implementation
procedure TMyClass.SetValue(const Value: string);
begin
FValue := Value;
end;
function TMyClass.GetValue: string;
begin
Result := FValue;
end;
procedure TMyClass.DoSomething;
begin
console.log('TMyClass.DoSomething');
end;
end.
---------------------------------------------------------
you don't actually need to declare that your class implements an interface.
Instead you just state what interface you need and let the compiler figure
out if the object can satisfy that need.
var MyStuff: IMyInterface;
MyStuff := TMyClass.Create as IMyInterface;
MyStuff.DoSomething;
the JS emitted would be something like this:
..........................................................................
var TObject={
$ClassName: "TObject",
$Parent: null,
ClassName: function (s) { return s.$ClassName },
ClassType: function (s) { return s },
ClassParent: function (s) { return s.$Parent },
$Init: function () {},
Create: function (s) { return s },
Destroy: function (s) { for (var prop in s) if (s.hasOwnProperty(prop))
delete s.prop },
Destroy$: function(s) { return s.ClassType.Destroy(s) },
Free: function (s) { if (s!==null) s.ClassType.Destroy(s) }
}
function $New(c) { var i={ClassType:c}; c.$Init(i); return i }
function AsInterface(o,i) {
if (o===null) return null;
var r = o.ClassType.Interface[i].map(function (e) {
return function () {
var arg=Array.prototype.slice.call(arguments);
arg.splice(0,0,o);
return e.apply(o, arg);
}
});
r.O = o;
return r;
};
var TMyClass = {
$ClassName:"TMyClass",$Parent:TObject
,$Init:function ($) {TObject.$Init($);
$.FValue = "";
}
,SetValue:function(Self, Value$1) {
Self.FValue = Value$1;
}
,GetValue:function(Self) {
var Result = "";
Result = Self.FValue;
return Result
}
,DoSomething:function(Self) { console.log("TMyClass.DoSomething"); }
,Destroy:TObject.Destroy
};
TMyClass.Interface={
IMyInterface:[TMyClass.SetValue, // 0
TMyClass.GetValue, // 1
TMyClass.DoSomething // 2
]}
MyStuff = AsInterface(TObject.Create($New(TMyClass)),"IMyInterface");
MyStuff[2]();
--
Sent from: http://pas2js.38893.n8.nabble.com/
More information about the Pas2js
mailing list