如何获取javascript对象的实际构造函数?

时间:2013-01-03 10:23:03

标签: javascript

有没有办法让实际的被调用函数用于实例化对象?

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"

我也对跨浏览器支持感兴趣

感谢

1 个答案:

答案 0 :(得分:1)

在这种继承之后,你需要显式设置'subclass'的构造函数。

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

据我所知,没有办法自动执行此操作。即使谷歌的Closure库也有这样的东西;

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

    subClass.prototype.constructor = subClass;
};   

所以,如果你有一个带参数的构造函数,你可以简单地做一些像

这样的事情
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