I am designing some class hierarchy in JavaScript. It works fine so far, but I can't see how to determine if an object is an "instance" of a parent class. Example:
function BaseObject(name){
this.name = name;
this.sayWhoAmI = function(){
console.log(this.name + ' is a Derivation1 : ' + (this instanceof Derivation1));
console.log(this.name + ' is a Derivation2 : ' + (this instanceof Derivation2));
console.log(this.name + ' is a BaseObject : ' + (this instanceof BaseObject));
};
}
function Derivation1(){
BaseObject.apply(this, ['first derivation']);
}
function Derivation2(){
BaseObject.apply(this, ['second derivation']);
}
var first = new Derivation1();
var second = new Derivation2();
first.sayWhoAmI();
logs this:
first derivation is a Derivation1 : true
first derivation is a Derivation2 : false
first derivation is a BaseObject : false
while second.sayWhoAmI();
logs this :
second derivation is a Derivation1 : false
second derivation is a Derivation2 : true
second derivation is a BaseObject : false
I feel like both first
and second
object should have say that they are instances of BaseObject
.
I understand that JavaScript may not be made for this, but I wonder if there's a way to achieve that.
Only calling
Base.apply(...)
does not setup inheritance. All that.apply
does is settingthis
to the first argument, nothing else. It is important to call the parent constructor, but it is not sufficient.What you have to do is setting up the prototype chain properly. That is, you have to set
Derivation1.prototype
to something that inherits fromBase.prototype
.Since each instance of a constructor function inherits from the constructor functions's prototype, you will see code such as
This is a bad idea and you can already see why:
Base
expects arguments to set up instance specific properties (name
in this case). But we don't care about these properties, since we are initialising them later in the child constructor withBase.apply(this, ...)
.So all we need is an object inheriting from
Base.prototype
and luckily, ECMASCript 5 defines a function which can do that for us (polyfill):This creates a new object inheriting from
Base.prototype
. Now, since you replaced the original prototype with a new object, you have to set theconstructor
property so that it points correctly toDerivation1
:Below is a complete example. Also have a look at this fiddle and this excellent answer by T.J. Crowder, which explains basically the same issues, but maybe in a better way.
Example: