原型继承和新关键字 [英] Prototypal inheritance and new keyword

查看:71
本文介绍了原型继承和新关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In backbone.js under the inherits method, the authors does this:

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

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

以上我理解的是允许新对象继承父对象的原型链。我试图围绕这个问题,但在实践中,上述内容与直接分配原型是否存在差异?

The above as I understand it is to allow the new object to inherit the prototypical chain of the parent. I'm trying to wrap my head around this, but in practice, is there a difference between the above and assigning the prototype directly?

child.prototype = parent.prototype

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

I understand that there exists this [[prototype]] object that cannot be accessed directly unless through the new keyword. However, given that most object declarations are of the form

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

上述原型作业的实际差异是什么?

What would be the practical differences in the above prototype assignments?

推荐答案

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

Remember that a prototype is an instance of the parent type. Using child.prototype = parent.prototype would set the child's prototype equal to the parent's prototype, rather than an prototypical instance of the parent.

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

Here's a huge problem that arises if you use child.prototype = parent.prototype: if you try to alter the child's prototype, you're also altering the parent's prototype, because they are the same object.

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

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

Creating the new instance of the parent is absolutely necessary. Otherwise, you'll have a flat prototype chain with a single shared prototype, so you'll have problems like the one I've outlined above.

这篇关于原型继承和新关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆