JSFiddle - React, Tailwind, and code Playground
by Andrea Aloi
JavaScript
console.clear();
/* Library 1 */
var L1 = {};
L1.A = function() {
console.log("A's constructor called");
};
L1.A.prototype.methodA = function() {
console.log("methodA called with arguments", arguments);
//heavy computation
};
L1.B = function() {
L1.A.call(this);
//Set a few other properties exclusive to B
};
L1.B.prototype = Object.create(L1.A.prototype);
/* Library2 */
var L2 = {};
for(prop in L1) {
//Assuming all props are methods, not properties
L2[prop] = function() {
//By default, inherited methods just call the super method
console.log("Default inherited constructor");
L1[prop].apply(this, arguments);
};
L2[prop].prototype = Object.create(L1[prop].prototype);
L2[prop].prototype.constructor = L2[prop];
/*
Shouldn't this be equivalent to the standard inheritance instructions?
L2.X = function() {...};
L2.X.prototype = Object.create(L1.X.prototype);
L2.X.prototype.constructor = L2.X;
*/
}
L2.B.prototype.constructor = function () {
//Now that I've created the prototype for L2.B, I just want to overload the constructor...
console.log("L2.B's constructor starts");
L1.B.apply(this, arguments);
console.log("L2.B's constructor ends");
}
L2.B.prototype.methodA = function() {
//...and methodA
console.log("Before invoking methodA()");
L1.B.prototype.methodA.apply(this, arguments);
console.log("After invoking methodA()");
};
var o1 = new L2.B();
console.log(o1); //Chrome says this is an instance of "L2.(anonymous function)"
//Instead, if I use code from previous comment (lines 32-34):
L2.B = function() {
//I just want to overload the constructor...
console.log("L2.B's constructor starts");
L1.B.apply(this, arguments);
console.log("L2.B's constructor ends");
};
L2.B.prototype = Object.create(L1.B.prototype);
L2.B.prototype.constructor = L2.B;
//and re-issue instructions as per lines 52-53:
o1 = new L2.B(); //Now it's using the...