为什么不在...中打印出来自Object的属性?

时间:2013-06-21 21:06:04

标签: javascript constructor prototypal-inheritance

我编写了以下javascript,并期望看到Obj2中的所有属性以及(我认为)将成为基类的属性 - 对象。为什么我看不到像prototype和toString这样的属性以及一个和两个?

Obj2 = function() {
   this.one = "one";
   this.two = "two";
}

var obj2 = new Obj2();

for(var i in obj2) {
    try {
        console.log(i + ": " + obj2[i]);
    }
    catch(e) {
        console.log(i + " caused error: " + e);
    }
}

1 个答案:

答案 0 :(得分:1)

正如lan所说,for ... in仅对可枚举属性进行迭代,如果你想获得实例的所有属性(可枚举与否),你可以尝试 Object.getOwnPropertyNames()

Live Demo

function Obj2() {
    this.one = "one";
    this.two = "two";
}

var obj2 = new Obj2(),
    proto = obj2,
    keys = Object.getOwnPropertyNames(proto);


while (proto) {
    for (var i in keys) {
        try {
            console.log(keys[i] + ": " + proto[keys[i]]);
        } catch (e) {
            console.log(i + " caused error: " + e);
        }
    }
    proto = Object.getPrototypeOf(proto);
    keys = proto ? Object.getOwnPropertyNames(proto) : null;
}