`__proto__`可以安全地用作使用“Object.create(null)”创建的对象的属性名称吗? [英] Is `__proto__` safe to use as a property name for objects created using `Object.create(null)`?
问题描述
这个问题的上下文是实现对可以放置在哪些键上没有限制的字典(没有有趣的行为)。
The context of this question is implementing dictionaries that have no restrictions on what keys can be placed in them (and no funny behavior).
当然,如果你使用继承自 Object.prototype
的对象,您可以获取有趣的行为,如果您尝试设置 __ proto __
。
Of course, if you use objects which inherit from Object.prototype
, you can get funny behavior if you try and set __proto__
.
所以问题是,如果您创建一个不从 Object.prototype
继承的对象,有没有什么特别的 __proto __
属性,它可以像任何其他属性名称一样安全吗?例如,在我的浏览器上 __ proto __
似乎对正常对象不安全,但在 Object.create(null)
对象:
So the question is, if you create an object that doesn't inherit from Object.prototype
, is there anything special about the __proto__
property, and is it as safe to use as any other property name? For example, on my browser __proto__
seems to be "unsafe" on "normal" objects, but "safe" on Object.create(null)
objects:
var normal = {};
Object.getPrototypeOf(normal) !== Array.prototype
normal['__proto__'] = Array.prototype;
Object.getPrototypeOf(normal) === Array.prototype // prototype **is** changed
var odd = Object.create(null);
Object.getPrototypeOf(odd) === null
odd['__proto__'] = Array.prototype;
Object.getPrototypeOf(odd) === null // prototype **not** changed
为了让我更加混淆,这个字典库使用 Object.create(null)
,还可以通过添加〜
来锁定密钥。这是否意味着一般来说,通过实现,在使用 Object.create(null)
创建的对象中使用任意键是不安全的。
To confuse me more, this dictionary library uses Object.create(null)
, but also mangles the keys by prepending a ~
. Does this mean that it is not safe, in general across implementations, to use arbitrary keys in objects created with Object.create(null)
?
推荐答案
正如我有最近学到的, __ proto __
本身不是一个特殊的属性;而 Object
原型的 __ proto __
属性,而扩展名为 __ proto __ $任何对象的c $ c>属性最终从
Obejct
原型继承。由于不是使用 Object.create(null)
创建的对象,所以 __ proto __
就像任何其他属性一样为他们(并且作为与上述链接的问题的例子,这也可以通过从原型链断开它们,从 Object
最初从 c> > myObejct .__ proto__ = null
。)
As I have recently learnt, __proto__
is not in itself a special property; rather the __proto__
property of the Object
prototype is, and by extension the __proto__
property of any object ultimately inheriting it from the Obejct
prototype. As this is not the case for objects created with Object.create(null)
, __proto__
is just like any other property for them. (And as the example in the question linked to above shows, this can also be acheived for objects originally inheriting from Object
by disconnecting them from the prototype chain with myObejct.__proto__ = null
.)
这篇关于`__proto__`可以安全地用作使用“Object.create(null)”创建的对象的属性名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!