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

时间:2019-05-15 19:11:11

标签: javascript html object

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

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

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

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

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

1 个答案:

答案 0 :(得分:2)

  

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)));