Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is `hasOwnProperty` not required?

When is hasOwnProperty not required?

The book JavaScript: The Good Parts includes the following which says that "it is usually necessary":

The other form (called for in) enumerates the property names (or keys) of an object. On each iteration, another property name string from the object is assigned to the variable.

It is usually necessary to test object.hasOwnProperty(variable) to determine whether the property name is truly a member of the object or was found instead on the prototype chain.

for (myvar in obj) {
 if (obj.hasOwnProperty(myvar)) {
 ...
 }
}

More specifically I want to enumerate the properties of a simple dictionary-like object, which is created using Javsacript object literal syntax, for example:

var foo = { 'bar': 'baz' };

or a similar object which is created using JSON.parse:

var foo = JSON.parse("{ 'bar': 'baz' }");

Should I use hasOwnProperty when I do for in on the foo object?

Assume that this javascript is running in a random browser as part of a complex web page.

Is the answer, "In practice it is probably/usually not necessary. In theory it could be necessary if some framework or library added a property by changing Object.prototype, but changing Object.prototype like that would be an intrusive bad practice which any respectable framework is unlikely to do"?

like image 604
ChrisW Avatar asked Mar 11 '23 05:03

ChrisW


1 Answers

IMHO, in modern JS interpreters it's almost[*] never required, and especially not for a plain object that's just being used as a dictionary.

jQuery manages just fine without it, because people have learnt that unsafely adding enumerable properties to Object.prototype is a bad idea.

ES5, of course, allows you to add non-enumerable properties to Object.prototype if you really want to, using Object.defineProperty.

[*] The exception to the above is if you're writing code that's specifically examining the prototype chain and really needs to know whether an enumerable property is inherited or not

like image 109
Alnitak Avatar answered Mar 23 '23 19:03

Alnitak