Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if Native JavaScript Object has a Property/Method?

Tags:

I thought this would be as easy as:

if(typeof(Array.push) == 'undefined'){   //not defined, prototype a version of the push method   // Firefox never gets here, but IE/Safari/Chrome/etc. do, even though   // the Array object has a push method! } 

And it does work fine in Firefox, but not in IE, Chrome, Safari, Opera, they return all properties/methods of the native Array object as 'undefined' using this test.

The .hasOwnProperty( prop ) method only works on instances... so it doesn't work, but by trial and error I noticed that this works.

//this works in Firefox/IE(6,7,8)/Chrome/Safari/Opera if(typeof(Array().push) == 'undefined'){   //not defined, prototype a version of the push method } 

Is there anything wrong with using this syntax to determine if a property/method exists on a Native Object / ~"JavaScript Class"~, or is there a better way to do this?

like image 413
scunliffe Avatar asked Feb 27 '09 17:02

scunliffe


1 Answers

The proper way to check if a property exists:

if ('property' in objectVar) 
like image 123
Barney Avatar answered Nov 07 '22 20:11

Barney