gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:52:02 27 4
gpt4 key购买 nike

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

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"

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

谢谢

最佳答案

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

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

Example .

关于javascript - 如何获取javascript对象的实际构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14136938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com