Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取javascript对象的实际构造函数?_Javascript - Fatal编程技术网

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

如何获取javascript对象的实际构造函数?,javascript,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" 我还对跨浏览器支持感兴趣 谢谢在这种继承之后,您需要显式

是否有一种方法可以获取用于实例对象的实际调用函数

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"
我还对跨浏览器支持感兴趣


谢谢

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

...
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
...
就我所知,没有办法自动做到这一点。甚至谷歌的闭包库也有类似的东西

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);
};

实际上,
console.log(x.constructor)
返回
函数A(){}
。“从不”使用
alert
进行调试,它将其参数转换为字符串()我想要得到函数B,我用来在
B.prototype=Object.create(A.prototype)之后实例化Object的函数
,尝试
B.prototype.constructor=B
@Rikonator没有一种方法可以自动执行此操作?好的,我明白了@如果你回答,我会接受你的回答