如果您在此页面上打开devtool并输入以下内容,则会得到:
let scripts = $$('script');
scripts[0].src // => "http://something....."
typeof scripts[0] // => "object"
但是如果我做Object.keys(scripts[0])
,我会得到:
Object.keys(scripts[0]); //=> []
为什么? HTMLScriptElement
不是对象吗?如果不是,那是什么?如何枚举其属性?
答案 0 :(得分:2)
Object.keys()返回一个数组,该数组的元素是与直接在对象上发现的可枚举属性相对应的字符串
来源:MDN
这意味着两件事:
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()));
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)));