Overview
hasOwnProperty()method is used to determine whether an object contains a specified property of its own.
Grammar
Obj.hasownproperty (prop)
Parameters
Describe
All inherited Object.prototype objects inherit from the prototype chain hasOwnProperty , which can be used to detect whether an object contains a specific property of its own, in unlike an operator, which ignores attributes inherited from the prototype chain.
ExampleExample 1: Using
hasOwnPropertymethod to determine whether an object contains a specific property of its own
The following example detects whether an object o contains its own propertiesprop:
o = new Object (); o.prop = ' exists '; function Changeo () {o.newprop = O.prop; Delete O.prop;} O.hasownproperty (' prop '); Returns True Changeo (); O.hasownproperty (' prop '); Returns false
Example 2: Differences between self-attributes and inherited attributes
The following example illustrates the hasOwnProperty difference between a method's handling of its own and inherited properties:
o = new Object (); o.prop = ' exists '; O.hasownproperty (' prop '); Returns True O.hasownproperty (' toString '); Returns false O.hasownproperty (' hasOwnProperty '); Returns false
Example 3: Traversing all of an object's own properties
The following example shows how to ignore inherited properties when traversing all the properties of an object, and note that this for..in loop only iterates through the enumerable properties, which is usually what we want, and the direct use Object.getOwnPropertyNames() method can implement similar requirements.
var Buz = {fog: ' stack '}; for (var name in Buz) {if (Buz.hasownproperty (name)) {alert ("This is fog (" + name + ") for sure. Value: "+ buz[name]); } else {alert (name); ToString or something else}}
Example 4:
hasOwnPropertyMethods are likely to be obscured
If an object has its own hasownproperty method, the same name method on the prototype chain is obscured (shadowed):
var foo = {hasownproperty:function () {return false; }, Bar: ' Here is Dragons '};foo.hasownproperty (' bar '); Always return false//If you are concerned about this situation, you can directly use the real hasOwnProperty method ({}) on the prototype chain. Hasownproperty.call (foo, ' Bar '); True Object.prototype.hasOwnProperty.call (foo, ' Bar '); True
JS "Object.prototype.hasOwnProperty () method"