let f = function () { this.a = 1; this.b = 2; }; let o = new f(); // {a: 1, b: 2} f.prototype.b = 3; f.prototype.c = 4; for(let i in o){
console.log(i) //a,b,c if(o.hasOwnProperty(i)){ console.log(i) //a,b } }
for...in
语句使您可以遍历对象的所有属性的名称。属性列表包括通过原型链继承的所有那些属性。所以需要 hasOwnProperty 过滤
for (name in object) { if (object.hasOwnProperty(name)) { doSomething(name); } }
但克隆对象时例外
for (prop in obj) { a[prop] = obj[prop]; // Compliant by exception }