检测功能是否是浏览器本身的功能 [英] Detect if function is native to browser

查看:75
本文介绍了检测功能是否是浏览器本身的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历网站中定义的所有全局变量,但是这样做我也获得了原生浏览器功能。

  var numf = 0; var nump = 0; var numo = 0; 
for(var p in this){
if(typeof(this [p])===function){
numf + = 1;
console.log(p +());
} else if(typeof p!='undefined'){
nump + = 1;
console.log(p);
} else {
numo + = 1;
console.log(p);






$ b

有没有一种方法可以确定一个函数是否是native到浏览器或在脚本中创建?

解决方案

您可以调用继承的 .toString()函数并检查结果。本地方法将有一个块,如 [native code]

  if (this [p] .toString()。indexOf('[native code]')> -1){
// yep,原生于浏览器
}






更新是因为很多评论员想要澄清一下,而且人们确实需要这样一个检测。为了让这个检查真的保存下来,我们应该使用下面这行代码:

  if(/ \ {\ s + \\ \\ [native code \] /。test(Function.prototype.toString.call(this [p]))){
// yep,native
}
.toString
方法从中添加



>原型 <函数这使得它非常不可能,如果不是不可能的话,某些其他脚本覆盖了 toString 方法。其次,我们用一个正则表达式来检查,所以我们不能被函数体内的注释所愚弄。


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; var numo=0; 
for(var p in this) { 
    if(typeof(this[p]) === "function"){
        numf+=1;
        console.log(p+"()");
    } else if(typeof p != 'undefined'){
        nump+=1;
        console.log(p);
    } else { 
        numo+=1;
        console.log(p);
    }
}

Is there a way to determine if a function is native to the browser or created in a script?

解决方案

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.

这篇关于检测功能是否是浏览器本身的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆