Detect if function is native to browser

前端 未结 5 1077
借酒劲吻你
借酒劲吻你 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:08

    I tried a different approach. This is only tested for firefox, and chrome.

    function isNative(obj){
        //Is there a function?
        //You may throw an exception instead if you want only functions to get in here.
    
        if(typeof obj === 'function'){
            //Check does this prototype appear as an object?
            //Most natives will not have a prototype of [object Object]
            //If not an [object Object] just skip to true.
            if(Object.prototype.toString.call(obj.prototype) === '[object Object]'){
                //Prototype was an object, but is the function Object?
                //If it's not Object it is not native.
                //This only fails if the Object function is assigned to prototype.constructor, or
                //Object function is assigned to the prototype, but
                //why you wanna do that?
                if(String(obj.prototype.constructor) !== String(Object.prototype.constructor)){
                    return false;
                }
            }
        }
        return true;
    }
    
    function bla(){}
    
    isNative(bla); //false
    isNative(Number); //true
    isNative(Object); //true
    isNative(Function); //true
    isNative(RegExp); //true
    

提交回复
热议问题