scunliffe
scunliffe

Reputation: 63588

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

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?

Upvotes: 25

Views: 49700

Answers (4)

bobince
bobince

Reputation: 536409

And it does work fine in Firefox

That's only by coincidence! You can't generally expect a prototype's method to also exist on the constructor function.

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

This was nearly right except you forget new, a perennial JavaScript gotcha. new Array().push, or [].push for short, would correctly check an instance had the method you wanted.

Upvotes: 3

Barney
Barney

Reputation: 631

The proper way to check if a property exists:

if ('property' in objectVar)

Upvotes: 62

ryan v
ryan v

Reputation: 134

The .hasOwnProperty can be accessed on the Array's proptotype, if typeof is not idiomatic enough.


if (Array.prototype.hasOwnProperty('push')) {
    // Native array has push property
}

Upvotes: 8

Peter Bailey
Peter Bailey

Reputation: 105898

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

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

When you execute typeof Array.push you are testing if the Array object itself has a push method, not if instances of Array have a push method.

Upvotes: 35

Related Questions