繁体   English   中英

为什么Object.keys不能与DOM节点一起使用?

[英]Why doesn't Object.keys work with DOM nodes?

如果您在此页面上打开devtool并输入以下内容,则会得到:

let scripts = $$('script');
scripts[0].src    // => "http://something....."
typeof scripts[0] // => "object"

但是,如果我执行Object.keys(scripts[0]) ,则会得到:

Object.keys(scripts[0]); //=> []

为什么? HTMLScriptElement不是对象吗? 如果不是,那是什么? 如何枚举其属性?

Object.keys()返回一个数组,该数组的元素是与直接在对象上发现的可枚举属性相对应的字符串

资料来源: MDN

这意味着两件事:

  1. 您没有得到继承的密钥:

 function foo() { this.a = 1; this.b = 2; this.c = 3; } // you get `a`, `b` and `c` as they are defined on the instance console.log(Object.keys(new foo())); function bar() { this.b = 2; this.c = 3; } bar.prototype.a = 1; // you don't get `a` as it is inherited from the prototype console.log(Object.keys(new bar())); 

  1. 而且您不会得到不可枚举的密钥:

 function foo() { this.a = 1; this.b = 2; this.c = 3; Object.defineProperty(this, 'a', {enumerable: false}); } console.log(Object.keys(new foo())) 


但是,您可以解决此问题:

 const s = document.querySelector('script'); console.log(Object.keys(Object.getPrototypeOf(s))); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM