This article describes in detail how to use hasOwnProperty () in javascript. it is very comprehensive and recommended to anyone who needs it.
Overview
The hasOwnProperty () method is used to determine whether an object contains the specified attributes.
Syntax
Obj. hasOwnProperty (prop)
Parameters
• Prop
• Name of the property to be detected.
Description
All inherited objects. all prototype objects are inherited from the prototype chain to the hasOwnProperty method. this method can be used to detect whether an object contains specific attributes, which is different from the in operator, this method ignores the attributes inherited from the prototype chain.
Example
Example 1: Use the hasOwnProperty method to determine whether an object contains specific attributes.
The following example checks whether the object o contains its own property prop:
The code is as follows:
O = new Object (); o. prop = 'exists'; function changeO (){
O. newprop = o. prop;
Delete o. prop;} o. hasOwnProperty ('prop ');
// Return true
ChangeO ();
O. hasOwnProperty ('prop ');
// Return false
Example 2: differences between attributes
The following example demonstrates the difference between the hasOwnProperty method and the inherited attributes:
The code is as follows:
O = new Object (); o. prop = 'exists'; o. hasOwnProperty ('prop ');
// Return true
O. hasOwnProperty ('tostring ');
// Return false
O. hasOwnProperty ('hasownproperties ');
// Return false
Example 3: traverse all attributes of an object
The following example demonstrates how to ignore the inheritance attribute when traversing all the attributes of an object .. the in loop only traverses the enumerated attributes, which is usually what we want and directly uses the Object. the getOwnPropertyNames () method can also meet similar requirements.
The code is 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: The hasOwnProperty method may be masked.
If an object has its own hasOwnProperty method, the method of the same name on the prototype chain will be masked (shadowed ):
The code is as follows:
Var foo = {
HasOwnProperty: function (){
Return false;
},
Bar: 'Here be Dragons'}; foo. hasOwnProperty ('bar ');
// Always return false
// If you are worried 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
The above is all the content described in this article. I hope you will like it.