- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定 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__
的原因在选项 2 和 prototype
中在选项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/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!