I know that classical pattern for inheritance with prototype is based to set the object prototype of the constructor function. However my willing is to have the possibility to call the parent constructor from the derived class constructor with some arguments that are not available before the call.
This is well accomplished in Java/Python/PHP with super(...)
or Parent.__init__(...)
method.
However in plain Javascript (not coffescript or similar) there is no way to do that ( parent.apply(this,arguments)
does but not it does not setup the prototype).
After some readings I've got this solution, adding the "inherits" method to the prototype of Function. This simply add the definition of super to the derived function in order to initialize the prototype according some parameters.
Function.prototype.inherits=function(parent)
{
var ctor=this;
var p=Object.create(parent);
ctor.super=function()
{
parent.apply(p,arguments);
}
ctor.prototype=p;
}
//testing
function A(x)
{
this.x=x;
}
function B(y)
{
B.super(y*2);//Here "super" is available and I can pass parameters.
this.y=y;
}
B.inherits(A);//here I define the inheritance
a=new A(3);
b=new B(5);
console.log(a);//returns { x: 3 }
console.log(b);//returns { y: 5 }
console.log(b.x);//returns 10
console.log(a instanceof A);//returns true
console.log(b instanceof B);//returns true
In this way I've got the behaviour that I expected. My question is: what are the drawbacks of this solution? Are there more efficent solutions to the same problem ? Is this solution cross-browser?
PS: I've invented it by myself :)
EDIT: in order to avoid collisions with other libraries I could define a standalone function like this that accomplish the same target.
function inherits(klass,parent)
{
var p=Object.create(parent);
klass.super=function()
{
parent.apply(p,arguments);
}
klass.prototype=p;
}
And in the testing after definition of B simply call
inherits(B,A);
EDIT 2:
After Moolamaduck consideration I have rewritten the code in order to solve the problem of shared prototype. The result is pretty simple to use and elegant (IMHO).
https://stackoverflow.com/a/33270707/76081