gpt4 book ai didi

javascript - 多态constructor.name属性访问

转载 作者:行者123 更新时间:2023-11-28 09:27:18 27 4
gpt4 key购买 nike

给定 JavaScript 代码:

function Parent() { ... }
function Child() { ... }

Child.prototype = new Parent();

// toString implementation on the parent object
Parent.prototype.toString = function() {
return this.constructor.name;
}

// And the code:
alert(new Child());

...当想要的结果是取回“Child”字符串时,将输出“Parent”(父 toString 实现中的 constructor.name 应该返回子构造函数名称)。

这在 JavaScript 中可能吗?

最佳答案

您在代码结果中看到的不一致是由两个原因引起的。首先,如果您使用 Object.getPrototypeOf(Child) 检查 Child 原型(prototype)对象你得到function Empty(){} ,因此要更正原型(prototype)对象分配,您应该使用 Child.__proto__ = new Parent()而不是Child.prototype = new Parent(); .第二个是原型(prototype)链的问题。如果你看到 Object.getPrototypeOf(Child) 的结果新分配后,您将得到 [object Object] (如果您还没有定义 Parent 原型(prototype) toString() 方法。如果定义了,那么它会返回 Parent(Child prototype) 原型(prototype) toString() 方法)这意味着 Child 有一个 对象 在其原型(prototype)属性中。那么你有三个选择:

1.为子对象本身分配一个toString()方法:

Child.toString = function(){ return this.name }

在这种情况下,您不应使用 this.constructor.name因为在原型(prototype)分配之后,其构造函数已更改为 Parent

2.定义子原型(prototype)(Parent) toString()方法:

Child.__proto__.toString = function(){ return this.name }

3.定义子原型(prototype)->prototype(Object) toString()方法:(覆盖)

Parent.prototype.toString = function(){ return this.name }

一些观察:

1.我使用__proto__的原因一开始的赋值是我想访问对象构造函数的原始原型(prototype)属性并更改它。

2.我用过return this.name因为这些方法将从 Child 调用,所以它引用了 Child 对象。

3.我使用__proto__的原因在选项 2prototype 中在选项3中我们使用__proto__当对象构造函数发生更改时,并且 prototype当对象构造函数没有改变时。

4.测试toString()您应该使用的方法 alert(Child)而是alert(new Child()) .

这里有一篇文章对您对原型(prototype)有很大帮助:

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

此答案的所有方面均已使用 Chrome JS 控制台进行了测试。

关于javascript - 多态constructor.name属性访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183862/

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