1

给定 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”(constructor.nametoString实现内部应该返回子构造函数名称)。

这在 JavaScript 中可能吗?

4

1 回答 1

0

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

1.将 toString() 方法分配给子对象本身:

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

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

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

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

3.define Child prototype->prototype(Object) toString()方法:(覆盖

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

一些观察:

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

2.我之所以使用return this.name这些方法是因为这些方法将从Child调用,所以它引用了Child Object。

3.我__proto__选项2选项3prototype中使用的原因是我们在Object构造函数更改时使用,并且在Object构造函数没有更改时使用。__proto__prototype

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

这是一篇对原型有很大帮助的文章:

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

这个答案的所有方面都使用 Chrome JS 控制台进行了测试。

于 2013-01-06T21:03:11.793 回答