Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a property exists in an object's prototype chain?

Tags:

javascript

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?

like image 273
FictionalCoder Avatar asked Mar 21 '14 18:03

FictionalCoder


1 Answers

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

like image 61
adeneo Avatar answered Sep 27 '22 18:09

adeneo