码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-19 20:16:29      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:first   分享图片   object   type   console   const   opp   span   pos   

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

标签:first   分享图片   object   type   console   const   opp   span   pos   

原文地址:https://www.cnblogs.com/Answer1215/p/9818445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!