How do you do inheritance in JavaScript without sharing the same instance of the super class between all instances of the sub class?
A common pattern is the following:
A temporary constructor is created, which inherits from the parent constructor's prototype. The child constructor's prototype is then set to an instance of the temporary constructor.
function inherits(Child, Parent) {
var Tmp = function() {};
Tmp.prototype = Parent.prototype;
Child.prototype = new Tmp();
Child.prototype.constructor = Child;
}
Inside the child constructor you then have to call the parent's constructor:
function Child(a, b, c) {
Parent.call(this, a, b);
}
inherits(Child, Parent);
// add prototype properties here
Inside this function call, this
will refer to the new object which gets created when you call new Child()
, hence, whatever initialization is performed inside Parent
, it is applied to the new object we pass.
But this will create a single instance of the super class and share it among all the instances of the sub class.
Yes, that's how inheritance works in JavaScript.
So is there a way to do this in JavaScript?
Not without horribly subverting/twising/misusing the existing paradigm. I recommend taking a different approach to implementing whatever you're aiming for.
This is how I have always done it.
// Parent object
function Thing(options)
{
//do stuff
}
Thing.prototype.someMethod = function(){
// some stuff
console.log('hello');
}
// child object which inherits from the parent
function OtherThing(options)
{
Thing.call(this, options);
// do stuff for otherthing
}
OtherThing.prototype = new Thing();
OtherThing.prototype.someMethod = function(){
// call things original function
Thing.prototype.someMethod.call(this);
// now do anything different
console.log('other thing says hi');
}
var testObj = new OtherThing();
testObj.someMethod();
Live Demo