2

I'm trying to list the functions defined by the user in javascript.

So far I have:

for (i in window)
    if (typeof(window[i])==='function')
        alert(window[i]);

jsfiddle: http://jsfiddle.net/sCK9v/1/

it only lists functions but (in Firefox) that includes a lot of system ones, listed as having [native code].

Is there a way to get the functions actually defined by the page?

4

3 回答 3

3

在所有其他脚本执行之前:

var nativeFunctions = (function(o, i){
    for(i in window){
         if(typeof window[i] =='function'){
             o[i] === true;
        }
     }
     return o;
}({}));

并且,当您想要检查新的全局函数时:

var userFunctions = (function(o, i){
    for(i in window){
         if(!nativeFunctions[i] && typeof window[i] =='function'){
             o[i] === true;
        }
     }
     return o;
}({}));
于 2013-07-24T22:22:23.503 回答
2

我认为hasOwnProperty应该已经过滤掉了所有的原生函数,因为它们是在 window 的原型中定义的,而不是在 window 本身中定义的:

for (i in window) {
    if (window.hasOwnProperty(i) && typeof(window[i]) === 'function') {
        alert(window[i]);
    }
}
于 2013-07-24T23:20:20.787 回答
2

如果你使用 Function.toString(); 你得到一个函数的主体,对于 Gekko (Firefox) 和 V8 (Chrome) 中的本机实现函数/绑定,这将返回一个字符串,如

“函数函数名(){[本机代码]}”

您可以按此过滤。

如果这不适合您,您需要编写一个词法分析器(或词法分析器)来找出文档中所有脚本标签中发生的事情

于 2013-07-24T22:14:20.560 回答