javascript 列出窗口对象的所有属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10374462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:39:18  来源:igfitidea点击:

List all properties of window object?

javascriptpropertieswindowprototype

提问by Graham

I'm looking to (dynamically) obtain a list of HTML elements the browser is currently aware of, such as HTMLPreElement, HTMLSpanElementetc. These objects are global, i.e.

我期待(动态)获得HTML元素的浏览器是目前知道的,比如列表HTMLPreElementHTMLSpanElement等等。这些对象是全球性的,即

console.log('HTMLPreElement' in window);  //=> true

So I thought I'd be able to use getOwnPropertyNameslike this:

所以我想我可以这样使用getOwnPropertyNames

console.log(Object.getOwnPropertyNames(window));

to obtain the full list of global properties (MDN states that this returns both enumerable and non-enumerable properties).

获取全局属性的完整列表(MDN 声明这会返回可枚举和不可枚举的属性)。

Using the above, I get an array with around 70 property nanes. But, it doesn't include objects like HTMLPreElement- only HTMLElement. I also tried:

使用上面的方法,我得到了一个包含大约 70 个属性 nanes 的数组。但是,这并不包括类似的对象HTMLPreElement-只HTMLElement。我也试过:

console.log(Object.getOwnPropertyNames(window.Window.prototype));

which brings back a bigger list (including addEventListeneretc) but again, no HTMLPreElement.

这带来了一个更大的列表(包括addEventListener等),但同样,没有HTMLPreElement

So, where the heck do these HTML{Tag}Elementobjects reside?

那么,这些HTML{Tag}Element对象到底存放在哪里呢?

采纳答案by Chopin

In Firefox, it seems to be the behavior of elements that their global object is not added unless explicitly requested as a global variable or property. Perhaps Firefox lazy loads them into the environment so that they don't consume memory unless they're actually needed.

在 Firefox 中,元素的行为似乎是不添加它们的全局对象,除非明确请求作为全局变量或属性。也许 Firefox 懒惰地将它们加载到环境中,这样它们就不会消耗内存,除非确实需要它们。

It seems that they do not show up when simply requesting the keys of the global object via Object.getOwnPropertyNamesunlessthey've first been explicitly referenced as described above.

似乎它们不会出现在简单地请求全局对象的键 via 时,Object.getOwnPropertyNames除非它们已经如上所述首先被显式引用。

http://jsfiddle.net/mBAHm/

http://jsfiddle.net/mBAHm/

回答by Chopin

for (var prop in window)
    console.log(prop);

That's what you need?

这就是你需要的?

回答by Michael Price

var obj = window;
while(obj){
    for(let prop of Reflect.ownKeys(obj)){
        console.log(prop);
    };
    obj = Object.getPrototypeOf(obj);
};