1

我编写了以下 javascript 并希望看到 Obj2 中列出的所有属性以及(我认为的)将是基类 - Object 的属性。为什么我没有看到像原型和 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);
    }
}
4

1 回答 1

1

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

现场演示

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;
}
于 2013-06-21T21:20:08.493 回答