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

Sam*_*Rad 5 html javascript object

如果您在此页面上打开开发工具并输入以下内容,您将得到:

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

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

Object.keys(scripts[0]); //=> []
Run Code Online (Sandbox Code Playgroud)

为什么?不是HTMLScriptElement一个物体吗?如果不是,那又是什么?如何枚举它的属性?

cus*_*der 4

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()));
Run Code Online (Sandbox Code Playgroud)

  1. 并且您不会获得不可枚举的键:

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

console.log(Object.keys(new foo()))
Run Code Online (Sandbox Code Playgroud)


不过,您可以解决此问题:

const s = document.querySelector('script');
console.log(Object.keys(Object.getPrototypeOf(s)));
Run Code Online (Sandbox Code Playgroud)