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

前端 未结 4 718
[愿得一人]
[愿得一人] 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: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.

提交回复
热议问题