myObject.hasOwnProperty( propertyOrMethodName ) in ECMAScript 262
Determines if the object/instance itself has the named property or method.
Arguments
name | type | description |
---|---|---|
propertyOrMethodName | String | The name of the property or me |
- Return Type
- Boolean
Description
This method returns true of the specific object instance or prototype has a property or method with the name specified. The inheritance chain is not searched. The following example illustrates this:
function Person(){ ... }
Person.prototype.breathe=function(){ ... }
var fredAstaire = new Person();
fredAstaire.dance = function(){ ... }
if (Person.prototype.hasOwnProperty('breathe')){
// this code will execute...the above call will return true
}
if (fredAstaire.hasOwnProperty('breathe')){
// this code will NOT execute...
// fredAstaire knows how to 'breathe', but this is an inherited method
}
if (fredAstaire.hasOwnProperty('dance')){
// this code will execute...the above call will return true
}
if (Person.prototype.hasOwnProperty('dance')){
// this code will NOT execute...
// not every Person knows how to dance
}
A common usage of this method is when iterating all properties/methods of an object instance, to only do something if the property/method is on the instance itself and not inherited:
for ( var propName in someObj ){
if ( someObj.hasOwnProperty( propName ) ){
...
}
}