快速Javascript继承:理解__proto__ [英] Quick Javascript inheritance: Understanding __proto__

查看:119
本文介绍了快速Javascript继承:理解__proto__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下构造函数,

Dog = function(name, age, ...){
    Animal.call(this, name, age, ...);
    // And some other stuff that dogs do
}

我用的是以下代码行从 Animal 类复制我的方法和属性,

I use the following line of code to copy my methods and properties across from the Animal class,

Dog.prototype = new Animal();

你能否告诉我这与

Dog.prototype.__proto__ = Animal.prototype;

因为它们似乎具有相同的效果。

since they seem to have the same effect.

推荐答案

__ proto __ 是JavaScript的非标准扩展(常见于各种解释器,但非标准),可直接为您提供访问对象后面的原型。函数对象的 prototype 属性是指定为通过新。因此,当您分配给 prototype .__ proto __ 时,您将分配对象背后的原型,该对象将被设置为函数创建的新对象的原型。

__proto__ is a non-standard extension to JavaScript (common in various interpreters, but non-standard) that gives you direct access to the prototype behind an object. The prototype property of function objects is the object that will be assigned as the prototype behind an object created by calling the function via new. So when you assign to prototype.__proto__, you're assigning to the prototype behind the object that will be set as the prototype on new objects created by the function.

由于原型链的工作方式是原型上的属性显示为对象上的继承属性(并且这在链中继续),如果您分配给 Dog.prototype .__ proto __ Dog 创建的对象将通过链间接访问这些属性:

Since the way the prototype chain works is that properties on a prototype show up as inherited properties on an object (and this continues in a chain), if you assign to Dog.prototype.__proto__, the objects created by Dog will have access to those properties indirectly through the chain:

+-----------------+      +----------------+      +-------------------------+
| instance of Dog |----->| Dog.prototype  |----->| Dog.prototype.__proto__ |
|                 |      |                |      | `foo` property          |
|                 |      |                |      | `bar` property          |
+-----------------+      +----------------+      +-------------------------+

直接分配给 Dog.prototype ,实例有更直接的参考:

When you assign directly to Dog.prototype, the instances have a more direct reference:

+-----------------+      +----------------+
| instance of Dog |----->| Dog.prototype  |
|                 |      | `foo` property |
|                 |      | `bar` property |
+-----------------+      +----------------+

(注意上面的略微误导,引用 Dog.prototype 就是这样。实例 Dog 将直接引用 Dog.prototype 上的对象,截至 new Dog ;如果稍后将一个完全不同的对象分配给 Dog.prototype ,则已存在的实例将具有旧原型,新实例将获得新的一个。但这是一个侧面点。)

(Note that the above is slightly misleading by referring to Dog.prototype like that. Instances of Dog will get a direct reference to the object on Dog.prototype as of when new Dog is called; if you assign a completely different object to Dog.prototype later, instances that already exist will have the old prototype and new instances will get the new one. But that's a side-point.)

这篇关于快速Javascript继承:理解__proto__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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