hasOwnProperty
To determine whether an object contains custom attributes rather than attributes on the prototype chain, we need to use the hasOwnProperty method that inherits from Object.prototype.
Note: It is not sufficient to determine whether a property is undefined or not. Because a property may indeed exist, its value is set to undefined.
hasOwnProperty is the only method in JavaScript that handles attributes but does not need to look up a prototype chain.
1 2 3 4 5 6 7 8 9 |
Modify Object.prototype Object.prototype.bar = 1; var foo = {goo:undefined}; Foo.bar; 1 ' bar ' in Foo; True Foo.hasownproperty (' Bar '); False Foo.hasownproperty (' goo '); True |
Only hasOwnProperty can give the correct and expected results, which is useful when traversing the properties of an object. There is no other way to exclude attributes from the prototype chain, rather than to define the properties on the object itself. hasOwnProperty as attributes (hasOwnProperty as a property)
JavaScript does not protect hasOwnProperty from being illegally occupied, so if an object happens to have this attribute, you need to use an external hasownproperty function to get the correct result.