我想看看原型链中的项目列表,有什么方法可以知道吗?我尝试使用getOwnPropertyNames,但它没有显示原型链
function Grid(width, height) {
this.width = width;
this.height = height;
}
Grid.prototype.example = function() {console.log("hello");}
console.log(Object.getOwnPropertyNames(new Grid()));
//["width", "length"]为什么它没有显示,有什么方法显示它吗?
此外,当从另一个构造函数继承属性时,使用getOwnPropertyNames时会出现一个奇怪的错误。
function Grid(width, height) {
this.space = new Array(width * height);
this.width = width;
this.height = height;
}
console.log(Object.getOwnPropertyNames(new Grid()));
//it gives me these errors
Uncaught RangeError: Invalid array length
at new Grid (<anonymous>:3:20)
at <anonymous>:2:40
at Object.InjectedScript._evaluateOn (<anonymous>:905:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:838:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)为什么会这样呢?
发布于 2015-08-02 06:37:37
我想最简单的方法是使用for循环:
for (var prop in obj) {
console.log(prop);
}如果要获取所有属性,而不仅仅是可枚举属性,则可以使用Object.getOwnPropertyNames和Object.getPrototypeOf的组合。
function getPropertyNames(obj) {
return obj ?
Object.getOwnPropertyNames(obj)
.concat(getPropertyNames(Object.getPrototypeOf(obj))) :
[];
}注意:此列表可以包含重复项。
https://stackoverflow.com/questions/31769195
复制相似问题