Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  169] [ 7]  / answers: 1 / hits: 49228  / 16 Years ago, fri, february 27, 2009, 12:00:00

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?

More From » methods


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 );

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.

[#99913] Monday, February 23, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 23
Total Questions: 106
Total Answers: 111

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago