Overview
The hasOwnProperty () method is used to determine whether an object contains a specified own property.
Grammar
Obj.hasownproperty (prop)
Parameters
prop
• The name of the property to be instrumented.
Describe
All objects inherited from the Object.prototype are inherited from the prototype chain to the hasOwnProperty method, which can be used to detect whether an object contains specific properties of itself, unlike the in operator, which ignores those inherited from the prototype chain.
Example
Example 1: Using the hasOwnProperty method to determine whether an object contains specific properties of itself
The following example detects whether object o contains its own properties prop:
Copy Code code as follows:
o = new Object (); o.prop = ' exists '; function Changeo () {
O.newprop = O.prop;
Delete O.prop;} O.hasownproperty (' prop ');
Returns True
Changeo ();
O.hasownproperty (' prop ');
return False
Example 2: Differences between self and inherited properties
The following example shows the difference between the hasOwnProperty method treating its own property and the inherited property:
Copy Code code as follows:
o = new Object (); o.prop = ' exists '; O.hasownproperty (' prop ');
Returns True
O.hasownproperty (' toString ');
return False
O.hasownproperty (' hasOwnProperty ');
return False
Example 3: Traversing all of the properties of an object
The following example shows how to ignore inherited properties when traversing all the properties of an object, and note here for ... The in loop only traverses the enumerable property, which is usually what we want, and the direct use of the Object.getownpropertynames () method can also achieve similar requirements.
Copy Code code as follows:
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:hasownproperty method may be obscured
If an object has its own hasOwnProperty method, the method of the same name on the prototype chain is obscured (shadowed):
Copy Code code as follows:
var foo = {
Hasownproperty:function () {
return false;
},
Bar: ' Here is Dragons '};foo.hasownproperty (' bar ');
Always return False
If you are worried about this, you can directly use the real hasOwnProperty method on the prototype chain
({}). hasownproperty.call (foo, ' Bar ');
True
Object.prototype.hasOwnProperty.call (foo, ' Bar ');
True
The above is the full content of this article, I hope you can enjoy.