显示javascript原型链

时间:2015-08-02 06:31:08

标签: javascript google-chrome

我想查看原型链中的项目列表 有没有办法知道它? 我尝试使用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)

为什么会这样?

1 个答案:

答案 0 :(得分:3)

我想最简单的方法是使用for循环:

for (var prop in obj) {
  console.log(prop);
}

如果您想要获取所有属性,而不仅仅是可枚举的属性,则可以使用Object.getOwnPropertyNamesObject.getPrototypeOf的组合:

function getPropertyNames(obj) {
  return obj ? 
    Object.getOwnPropertyNames(obj)
      .concat(getPropertyNames(Object.getPrototypeOf(obj))) :
    [];
}

注意:此列表可以包含重复项。

相关问题