[Javascript] Use JavaScript's for-in Loop on Objects with Prototypes

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] Use JavaScript's for-in Loop on Objects with Prototypes相关的知识,希望对你有一定的参考价值。

Loops can behave differently when objects have chained prototype objects. Let\'s see the difference we get when we use the for-in loop on an object without a prototype, as opposed to an object with a prototype object.

 

Let\'s say you have an object:

const obj = {
  firstName: "Bar",
  lastName: "Foo"
};

 

Once you use for in loop:

for (let property in obj) {
    console.log(property); // firstName, lastName
    n++;    
}
console.log(n); // 2

 

We can add one prototype prop to the obj:

const protoObj = {
  hair: "Brown"
};

Object.setPrototypeOf(obj, protoObj);

 

 

On the prototype chain we have \'hair\' prop.

 

Now, if you use for in loop again:

for (let property in obj) {

    console.log(property); //firstName, lastName, hair
    n++;
  
}
console.log(n); // 3

 

Be to notice, \'hair\' is on the prototype chain,is not on obj\'s own property, so if we want to fileter \'hair\':

for (let property in obj) {
  if (obj.hasOwnProperty(property)) {
    console.log(property); // firstName, lastName
    n++;
  }
}
console.log(n); // 2

 

以上是关于[Javascript] Use JavaScript's for-in Loop on Objects with Prototypes的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript基础

前端——JavaScript

javascript初识

如何使用javascript将svg use元素插入svg组?

JavaScript 运行机制

JavaScript??????0-100????????????