2

在继承方法下的backbone.js中,作者这样做:

var ctor = function() {};
// some other code ...

var child;
// some other code ...
ctor.prototype = parent.prototype;
child.prototype = new ctor();

据我了解,以上是允许新对象继承父对象的原型链。我试图解决这个问题,但在实践中,上述内容与直接分配原型之间有区别吗?

child.prototype = parent.prototype

我知道存在这个 [[prototype]] 对象,除非通过 new 关键字,否则无法直接访问。但是,鉴于大多数对象声明的形式为

var SomeObj = function() {};
SomeObj.prototype.test = function() { return "Hello World"; }

上述原型分配的实际差异是什么?

4

2 回答 2

3

请记住,原型是父类型的实例。使用child.prototype = parent.prototype会将孩子的原型设置为等于父母的原型,而不是父母的原型实例。

如果你使用 : 会出现一个大问题child.prototype = parent.prototype:如果你试图改变孩子的原型,你也改变了父母的原型,因为它们是同一个对象。

Child.prototype.childOnlyValue = 5;
// WARNING: Parent.prototype.childOnlyValue is now also 5,
//             because Parent.prototype === Child.prototype

创建父级的新实例是绝对必要的。否则,您将拥有一个带有单个共享原型的扁平原型链,因此您将遇到我上面概述的问题。

于 2012-05-01T05:39:02.420 回答
0

这是描述上述情况的脚本

var x = {
    // do nothing
};

var a = function() {};

a.prototype = x;

var b = new a();
console.log("b.__proto__ is x? " + (b.__proto__ == x)); // true

var c = function() {};
c.prototype = new a();
console.log("c prototype.__proto__ is x? " + (c.prototype.__proto__ == x)); // true

var anotherFn = function() {
    // do nothing
};
c.prototype.aFn = anotherFn;

var d = new c();
console.log("d __proto__^2 is x?" + (d.__proto__.__proto__ == x)); // true
console.log("d __proto__.aFn is anotherFn? " + (d.__proto__.aFn == anotherFn)); // true
于 2012-05-01T23:17:00.773 回答