Detect if function is native to browser

前端 未结 5 1081
借酒劲吻你
借酒劲吻你 2020-11-30 07:38

I am trying to iterate over all the globals defined in a website, but in doing so I am also getting the native browser functions.

var numf=0; var nump=0; v         


        
5条回答
  •  感动是毒
    2020-11-30 08:05

    You can call the inherited .toString() function on the methods and check the outcome. Native methods will have a block like [native code].

    if( this[p].toString().indexOf('[native code]') > -1 ) {
        // yep, native in the browser
    }
    

    Update because a lot of commentators want some clarification and people really have a requirement for such a detection. To make this check really save, we should probably use a line line this:

    if( /\{\s+\[native code\]/.test( Function.prototype.toString.call( this[ p ] ) ) ) {
        // yep, native
    }
    

    Now we're using the .toString method from the prototype of Function which makes it very unlikely if not impossible some other script has overwritten the toString method. Secondly we're checking with a regular expression so we can't get fooled by comments within the function body.

提交回复
热议问题