2

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

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"

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

谢谢

4

1 回答 1

1

在这种继承之后,您需要显式设置“子类”的构造函数。

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

据我所知,没有办法自动执行此操作。甚至 Google 的 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);
};

例子

于 2013-01-03T10:58:11.790 回答