javascript oop, instanceof and base class

Viewed 4600

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.

1 Answers
Related