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

前端 未结 4 694
[愿得一人]
[愿得一人] 2020-12-24 07:38

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          


        
相关标签:
4条回答
  • 2020-12-24 07:43

    The proper way to check if a property exists:

    if ('property' in objectVar)
    
    0 讨论(0)
  • 2020-12-24 07:52

    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.

    0 讨论(0)
  • 2020-12-24 07:57

    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.

    0 讨论(0)
  • 2020-12-24 08:02

    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
    }
    
    
    0 讨论(0)
提交回复
热议问题