Goodword
Goodword

Reputation: 1645

in this particular example, why did the author use the if...hasOwnProperty in a for...in loop pattern?

I have read the following articles about how using has own property prevents you from enumerating over properties defined on the prototype of an object:

-MDN hasOwnProperty

-How do I check if an object has a property in JavaScript?

-for..in and hasOwnProperty

I think I get how the pattern works in general and why you would use it, but I still don't understand why, in the following code from CH 19 of Eloquent Javascript, the author has chosen to use this pattern...

function elt(name, attributes) {
  var node = document.createElement(name);
  if (attributes) {
    for (var attr in attributes)              
      if (attributes.hasOwnProperty(attr))       // <----------------
        node.setAttribute(attr, attributes[attr]);
  }
  for (var i = 2; i < arguments.length; i++) {
    var child = arguments[i];
    if (typeof child == "string")
      child = document.createTextNode(child);
    node.appendChild(child);
  }
  return node;
}

The use for this function, by the way, is:

It creates an element with the given name and attributes and appends all further arguments it gets as child nodes, automatically converting strings to text nodes.

Could someone walk me through this particular example?

Upvotes: 0

Views: 85

Answers (1)

jfriend00
jfriend00

Reputation: 707466

The structure for (var attr in attributes) iterates all iterable properties, including items on the prototype.

If you only want to iterate properties that are actually assigned directly to the object, but not properties that are on the prototype, then you can filter them out using .hasOwnProperty() as the code you pointed to does. That code will skip any iterable properties on the prototype and will only iterate properties on the actual object itself.

Upvotes: 1

Related Questions