JavaScript中的全局用户定义函数列表?

Ann*_*nan 29 javascript function

是否可以在JavaScript中获取用户定义函数的列表?

我目前正在使用它,但它返回非用户定义的函数:

var functionNames = [];

for (var f in window) {
    if (window.hasOwnProperty(f) && typeof window[f] === 'function') {
        functionNames.push(f);
    }
}
Run Code Online (Sandbox Code Playgroud)

Che*_*try 19

我假设您想要过滤掉本机功能.在Firefox中,Function.toString()返回函数体,对于本机函数,它将采用以下形式:

function addEventListener() { 
    [native code] 
}
Run Code Online (Sandbox Code Playgroud)

您可以匹配/\[native code\]/循环中的模式并省略匹配的函数.


raz*_*zak 9

正如Chetan Sastry在他的回答中建议的那样,你可以检查[native code]字符串化函数内部是否存在:

Object.keys(window).filter(function(x)
{
    if (!(window[x] instanceof Function)) return false;
    return !/\[native code\]/.test(window[x].toString()) ? true : false;
});
Run Code Online (Sandbox Code Playgroud)

或者干脆:

Object.keys(window).filter(function(x)
{
    return window[x] instanceof Function && !/\[native code\]/.test(window[x].toString());
});
Run Code Online (Sandbox Code Playgroud)

在chrome中,您可以通过以下方式获取所有非原生变量和函数:

Object.keys(window);
Run Code Online (Sandbox Code Playgroud)