在下面的代码中,我得到 true
,这意味着至少在 Chrome 和 Firefox 中,属性 someMagic
是 obj
自己的属性。
但是当我尝试通过 getOwnPropertyNames 获取完整的属性列表时,返回的数组在两个浏览器中都不包含它。在 chrome 中,我收到单个属性 constructor
,而在 FF 中,结果是一个空数组。为什么?
是否可以获取所有名称?
var obj = Object.getPrototypeOf(Object.getPrototypeOf(window))
console.log(obj.hasOwnProperty('someMagic'))
console.log(Object.getOwnPropertyNames(obj))
<div id="someMagic"></div>
最佳答案
正如 @Bergi 在他的评论中所说,window
对象被名为 WindowProxy 的东西包裹着。 。正如他所说:充满异国情调,像代理一样(而且古怪而神奇:-)。规范中的更多详细信息:
A WindowProxy is an exotic object that wraps a Window ordinary object, indirecting most operations through to the wrapped object. Each browsing context has an associated WindowProxy object. When the browsing context is navigated, the Window object wrapped by the browsing context's associated WindowProxy object is changed.
The WindowProxy exotic object must use the ordinary internal methods except where it is explicitly specified otherwise below.
关于使用普通内部方法的最后一部分“除非......明确指定”是关键。
在 EcmaScript 262 standard ,它指定 hasOwnProperty
使用 GetOwnProperty
。 getOwnPropertyNames
使用 OwnPropertyKeys
。请注意,这两个内容都在 WindowProxy
中被覆盖:
7.4.5 [[GetOwnProperty]] ( P )
7.4.10 [[OwnPropertyKeys]] ( )
因此,您上面使用的两个属性都使用重写的非普通方法,而不是“普通内部方法”。因此他们给出了不寻常的结果。 7.4.5 GetOwnProperty
下甚至有一个警告,警告“故意违反”规范:
This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing Web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]
这个StackOverflow Answer详细介绍了这种奇怪行为如何成为 HTML5
标准一部分的历史。
关于javascript - 获取所有属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59778685/