gpt4 book ai didi

javascript - 为什么在 OOP javascript 中使用 object.prototype.constructor ?

转载 作者:行者123 更新时间:2023-12-03 03:21:56 25 4
gpt4 key购买 nike

我最近开始阅读 OOP javascript,作者似乎跳过的一件事是,当声明一个对象 A 时,我突然看到“A.prototype.constructor =A;例如,

var A = function(){}; // This is the constructor of "A"
A.prototype.constructor = A;
A.prototype.value = 1;
A.prototype.test = function() { alert(this.value); }
var a = new A(); // create an instance of A
alert(a.value); // => 1

所以我在 firebug 中运行命令“var A = function(){};”然后是“A.Constructor”,它揭示了它是一个函数。我明白这一点。
我运行代码“A.prototype.constructor = A;”我认为这将 A 构造函数从 Function 更改为 A。

A 的构造函数属性已更改,对吗?相反,当我运行“A.constructor”时,它仍然给我 function () 。

有什么意义?

我还看到 A.constructor.prototype.constructor.prototype.. 发生了什么事?

最佳答案

如果 A 使用 A.prototype = new B(); 继承 B,则需要使用 A.prototype.constructor=A; 重置类 A 的构造函数属性 code>,否则 A 的实例将具有 B 的构造函数。

在您的情况下,A.prototype.constructor === A 将返回 true,因此 A.prototype.constructor = A 不执行任何操作。

关于javascript - 为什么在 OOP javascript 中使用 object.prototype.constructor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074556/

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