当前位置 : 主页 > 大数据 > 区块链 >

[[Prototype]]和原型在JavaScript中的关系

来源:互联网 收集:自由互联 发布时间:2021-06-22
从 http://www.jibbering.com/faq/faq_notes/closures.html: Note: ECMAScript defines an internal [[prototype]] property of the internal Object type. This property is not directly accessible with scripts, but it is the chain of objects refer
从 http://www.jibbering.com/faq/faq_notes/closures.html:

Note: ECMAScript defines an internal [[prototype]] property of the internal Object type. This property is not directly accessible with scripts, but it is the chain of objects referred to with the internal [[prototype]] property that is used in property accessor resolution; the object’s prototype chain. A public prototype property exists to allow the assignment, definition and manipulation of prototypes in association with the internal [[prototype]] property. The details of the relationship between to two are described in ECMA 262 (3rd edition) and are beyond the scope of this discussion.

两者之间关系的细节是什么?我已浏览过ECMA 262,所有我读过的东西就像:

The constructor’s associated prototype can be referenced by the program expression constructor.prototype,

Native ECMAScript objects have an internal property called [[Prototype]]. The value of this property is either null or an object and is used for implementing inheritance.

Every built-in function and every built-in constructor has the Function prototype object, which is the initial value of the expression Function.prototype

Every built-in prototype object has the Object prototype object, which is the initial value of the expression
Object.prototype (15.3.2.1), as the value of its internal [[Prototype]] property, except the Object
prototype object itself.

从这一切我收集的是[[Prototype]]属性相当于几乎任何对象的原型属性。我错了吗

在大多数情况下,我相信你是对的。

每个对象都有一个隐藏的[[Prototype]]属性,用于继承。函数另外有一个公共原型属性,仅当该函数用作构造函数时才使用:当使用new构造对象时,新对象的[[Prototype]]属性设置为函数的原型属性,即用作构造函数。

例如。

function C() {}
C.prototype = P1;  
var obj = new C();  // obj.[[Prototype]] is now P1.

您可以使用Object.getPrototypeOf(< obj>)获取[[Prototype]]属性。 (此方法在ECMAScript 5中指定。较旧版本的JavaScript没有任何标准的阅读方式[[Prototype]])。

您通常可以通过构造函数获得原型,例如:

obj.constructor.prototype == Object.getPrototypeOf(obj)

但是并不总是如此,因为可以重新分配构造函数的prototype属性,而是在创建对象后无法重新分配对象的[[Prototype]]。所以如果你这样做:

C.prototype = P2;

然后

obj.constructor.prototype != Object.getPrototypeOf(obj)

因为C的原型现在是P2,而obj的[[Prototype]]仍然是P1。

请注意,它只是具有原型属性的函数。还要注意,函数的prototype属性与函数的[[Prototype]]属性不同!

网友评论