Inheriting A Class That Has The Same Constructor But Different/similar Prototypes
Suppose I have a constructor: function Constructor(input) { this.input = input } Constructor.prototype.method = function() { console.log('a') } But I want to make another cla
Solution 1:
var inherits = function(childCtor, parentCtor) {
/** @constructor */functiontempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = newtempCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
};
// How to use it:varConstructor1 = function() {
//add all your methods, variables etc
};
Constructor1.prototype.myMethod = function() {
};
varContructor2 = function() {
Contructor1.call(this); // Call the super class constructor
};
inherits(Contstructor2, Constructor1);
// Constructor2 now inherits from Constructor1// override, add methods variables etc, whatever you need.// Have fun!
Solution 2:
Okay, much easier just to use apply
:
functionnewConstructor(Super) {
functionConstruct() {
Super.apply(this, arguments)
}
require('util').inherits(Construct, Super)
returnConstruct
}
Solution 3:
Here's a nasty-ish solution:
functionConstructor1(input) {
this.input = input;
}
Constructor1.prototype.method = function() {
console.log('a');
}
// be careful here: evals the string value of Constructor1 with references to "Constructor1" changed to "Constructor2"eval(Constructor1.toString().replace("Constructor1", "Constructor2"));
Constructor2.prototype.method = function() {
console.log('b');
}
var c1 = newConstructor1(1);
var c2 = newConstructor2(2);
console.log(c1.constructor === c2.constructor) // true
c1.method() // a
c2.method() // b
Post a Comment for "Inheriting A Class That Has The Same Constructor But Different/similar Prototypes"