I am a newbie in Javascript and trying to learn this language. After going through several posts I figured out that in order to check an Object's particular property we can broadly use one of the following methods.
1] Using hasOwnProperty
Object.hasOwnProperty("propertyName")
However this does not check properties inherited from the Object's prototype chain.
2] Loop over all the properties and check if property exists.
for(propertyName in myObject) {
    // Check if "propertyName" is the particular property you want.
}
Using this you can check Object's properties in the prototype chain too.
My question is: Is there a method other than 2] by which I can check if "propertyName" is a property in Object's prototype chain? Something similar to "hasOwnProperty" and without looping?
You can just check the property directly with in, and it will check the prototype chain as well, like this
if ('propertyName' in myObject)
an example
var obj = function() {};
obj.prototype.test = function() {};
var new_obj = new obj();
console.log( 'test' in new_obj ); // true
console.log( 'test22222' in new_obj ); // false
console.log( new_obj.hasOwnProperty('test') ); // false
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With