FictionalCoder
FictionalCoder

Reputation: 115

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

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?

Upvotes: 7

Views: 4190

Answers (2)

Mihey Mik
Mihey Mik

Reputation: 1862

Reflect.has can make a work for you

console.log(Reflect.has({}, 'toString')); // true

Upvotes: 1

adeneo
adeneo

Reputation: 318252

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

Upvotes: 9

Related Questions