gpt4 book ai didi

javascript - JavaScript 中 [[Prototype]] 与原型(prototype)的关系

转载 作者:行者123 更新时间:2023-12-03 01:29:35 25 4
gpt4 key购买 nike

来自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 expressionObject.prototype (15.3.2.1), as the value of its internal [[Prototype]] property, except the Objectprototype object itself.

据我所知,[[Prototype]] 属性相当于几乎任何对象的 prototype 属性。我是不是搞错了?

最佳答案

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

每个对象都有一个隐藏的[[Prototype]]属性(property),用于继承。函数另外还有一个 public prototype属性,仅当函数用作构造函数时使用:当使用 new 构造对象时,[[Prototype]]新对象的属性设置为 prototype用作构造函数的函数的属性。

例如

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

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

您通常可以通过构造函数获取原型(prototype),例如:

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

但情况并非总是如此,因为构造函数的原型(prototype)属性可以重新分配,但[[Prototype]]对象创建后不能重新分配对象的属性。所以如果你这样做:

C.prototype = P2;

然后

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

因为C的原型(prototype)现在是P2 ,但是[[Prototype]]obj仍然是P1 .

请注意,只有函数具有 prototype属性(property)。另请注意 prototype函数的属性与 [[Prototype]] 不同函数的属性!

关于javascript - JavaScript 中 [[Prototype]] 与原型(prototype)的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/383201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com