javascript - 获取所有属性名称

标签 javascript google-chrome

在下面的代码中,我得到 true ,这意味着至少在 Chrome 和 Firefox 中,属性 someMagicobj 自己的属性。

但是当我尝试通过 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 使用 GetOwnPropertygetOwnPropertyNames 使用 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/

相关文章:

javascript - 如何在 React Native 中垂直居中项目

javascript - Jquery 客户端验证不起作用

javascript - 如何禁用取消选择时所需的

javascript - "Un-redefining"Google Chrome 的控制台对象

css - 在我重新设计时无法让 iFrame 在 Internet Explorer 中工作

javascript - 有没有办法在 Chrome 的检查器中实时查看哪些 Javascript 函数(函数的名称)执行?

javascript - 使用 react.renderToStaticMarkup 获取换行符/缩进?

javascript - 如何根据自定义逻辑扩展一个数组以适应另一个数组的相同长度?

mozilla 的 css 和 chrome 的 css

google-chrome - 适用于 Centos/Linux 的 Google chrome 旧版本