Overview
The hasOwnProperty() method is used to determine whether an object contains a specified property.
grammar
obj.hasOwnProperty(prop)
parameter
•prop
•The name of the attribute to be detected.
describe
All objects that inherit Object.prototype will be inherited from the prototype chain to the hasOwnProperty method. This method can be used to detect whether an object contains a specific property. Unlike the in operator, this method will ignore the properties inherited from the prototype chain.
Example
Example 1: Use the hasOwnProperty method to determine whether an object contains a specific property
The following example detects whether object o contains its own attribute prop:
The code copy 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: The difference between your own attributes and inherited attributes
The following example demonstrates the difference between the hasOwnProperty method treats its own properties and inherited properties:
The code copy is as follows:
o = new Object();o.prop = 'exists';o.hasOwnProperty('prop');
// Return true
o.hasOwnProperty('toString');
// Return false
o.hasOwnProperty('hasOwnProperty');
// Return false
Example 3: Iterate through all the properties of an object
The following example demonstrates how to ignore inherited properties when traversing all properties of an object. Note that the for..in loop will only traverse enumerable properties, which is usually what we want. It can also achieve similar requirements directly using the Object.getOwnPropertyNames() method.
The code copy 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 blocked
If an object has its own hasOwnProperty method, the method of the same name on the prototype chain will be shadowed:
The code copy 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, 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 like it.