How to determine if a native JavaScript object has a Property / Method?

I thought it would be as simple 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 works fine in Firefox, but not in IE, Chrome, Safari, Opera , they return all the properties / methods of their own Array object as 'undefined' using this test.

The .hasOwnProperty (prop) method only works with instances ... so it doesn’t work, but with trial and error, I noticed that it 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 in a Native Object / ~ "JavaScript Class" ~, or is there a better way to do this?

+17
javascript methods properties native typeof
Feb 27 '09 at 17:33
source share
4 answers

First of all, typeof is an operator, not a function, so you don't need parentheses. Secondly, refer to the prototype of the object.

 alert( typeof Array.prototype.push ); alert( typeof Array.prototype.foo ); 

When you execute typeof Array.push , you check to see if the Array object has a push method, and not if the array instances have a push method.

+30
Feb 27 '09 at 17:41
source share

The correct way to check if a property exists is:

 if ('property' in objectVar) 
+50
Mar 21 '10 at 20:00
source share

Access to .hasOwnProperty can be obtained in the prototype Array if typeof not idiomatic enough.

 if (Array.prototype.hasOwnProperty('push')) { // Native array has push property }
if (Array.prototype.hasOwnProperty('push')) { // Native array has push property } 
+7
Apr 19 '10 at 22:14
source share

And it works fine in Firefox

This is just a coincidence! Normally, you cannot expect that the prototype method also exists in the constructor function.

 if(typeof(Array().push) == 'undefined') 

This was almost correct, except that you forgot new , multi-year-old JavaScript code. new Array().push or [].push for short, would check the instance correctly if you wanted to.

+2
Feb 27 '09 at 17:54
source share



All Articles