ZHONGJIAFENG
ZHONGJIAFENG

Reputation: 53

JavaScript inherit object values

enter image description here

enter image description here

in extend() function, the output of the source is

{ add: [Function: add], show: [Function: show] } see line 14

but in for-loop there are another new property called extend?? why

Upvotes: 0

Views: 63

Answers (1)

spirift
spirift

Reputation: 3062

A for loop will look into the prototype chain of an object. Here is a good article on it.

To avoid this, inside the loop you can make an if statement that checks if the property is part of the object.

for (var name in buz) {
  if (buz.hasOwnProperty(name)) {
    console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
  }
  else {
    console.log(name); // toString or something else
  }
}

See more details about hasOwnProperty.

Upvotes: 2

Related Questions