user652649
user652649

Reputation:

how to get the actual constructor of a javascript object?

is there a way to get the actual called function used to instance the object?

function A(){}
A.prototype.test = function(){};

function B(){}
B.prototype = Object.create(A.prototype);

B.prototype.test = function(){};

var x = new B();
alert(x.constructor);   // alerts "A"

i'm also interested in cross browser support

thanks

Upvotes: 2

Views: 88

Answers (1)

Rikonator
Rikonator

Reputation: 1860

After this sort of inheritance, you need to explicitly set the constructor of the 'subclass'.

...
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
...

As far as I'm aware, there is no way to do this automatically. Even Google's Closure library has something like this;

var inherit = function(subClass, superClass) {
    var temp = function() {};
    temp.prototype = superClass.prototype;
    subClass._super = superClass.prototype;
    subClass.prototype = new temp();

    subClass.prototype.constructor = subClass;
};   

So, if you have a constructor with arguments, you can simply do something like

var ParentClass = function(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
};

ParentClass.prototype.show = function() {
    console.log('Parent!');
    console.log('arg1: ' + this.arg1);
    console.log('arg2: ' + this.arg2);
};

var ChildClass = function(arg1, arg2, arg3) {
    ParentClass.call(this, arg1, arg2);
    this.arg3 = arg3;
};

inherit(ChildClass, ParentClass);

ChildClass.prototype.show = function() {
    console.log('Child!');
    console.log('arg1: ' + this.arg1);
    console.log('arg2: ' + this.arg2);
    console.log('arg3: ' + this.arg3);
};

Example.

Upvotes: 1

Related Questions