我编写了以下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);
}
}
答案 0 :(得分: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;
}