原型继承和新关键字

Prototypal inheritance and new keyword

本文关键字:关键字 继承 原型      更新时间:2023-09-26

在 backbone.js 在 inherits 方法下,作者这样做:

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

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

child.prototype = parent.prototype

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

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

上述原型作业的实际区别是什么?

请记住,原型是父类型的实例。使用 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

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

这是一个描述上述情况的脚本

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