检查JavaScript函数是否返回而不执行它?

Mes*_*aal 7 javascript conditional return function

我有一个给定的函数,除了其他参数之外,还有两个可选参数,它们可能是函数.两者都需要是可选的,一个是函数,一个是布尔值或返回布尔值的函数.

// Obj.func(variable, String[, Object][, Boolean||Function][, Function]);
Obj.func = function(other, assorted, args, BoolOrFunc, SecondFunc) {
    // execution
};

Obj.func(
    [
        'some',
         'data'
    ],
    'of varying types',
    {
        and: 'some optional arguments'
    },
    function() {
        if(some condition) {
            return true;
        }
        return false;
    },
    function() {
       // do things without returning
    }
);
Run Code Online (Sandbox Code Playgroud)

我希望两个函数(以及其他几个参数,如果重要)是可选的,这意味着我在函数中有代码来确定用户打算使用哪些参数.

不幸的是,因为两者都可能是函数,并且可能直接在函数调用中指定,所以我不能简单地使用typeofinstanceof条件.但是,由于第一个函数(如果存在)将始终返回一个布尔值(并且第二个函数根本不会返回),我有一个想法是检查它的返回值:

if(typeof BoolOrFunc === 'boolean'
   || (typeof BoolOrFunc === 'function' && typeof BoolOrFunc() === 'boolean')) {
    // BoolOrFunc is either a boolean or a function that returns a boolean.
    // Handle it as the intended argument.
} else {
    // Otherwise, assume value passed as BoolOrFunc is actually SecondFunc,
    // and BoolOrFunc is undefined.
}
Run Code Online (Sandbox Code Playgroud)

这原则上有效; 但是,运行会typeof BoolOrFunc()执行函数,如果函数不仅仅返回一个布尔值,那么会导致问题:即,如果函数传递BoolOrFunc确实是这样的话SecondFunc.SecondFunc在这种情况下,它是一个回调函数,可以执行我不想立即执行的操作,包括DOM修改.

出于这个原因,我的问题是:有没有办法检查函数是否返回而不执行它?

我考虑过的一件事是调用BoolOrFunc.toString(),然后执行正则表达式搜索返回值,类似于...

if(typeof BoolOrFunc === 'boolean'
   || (typeof BoolOrFunc === 'function'
       && BoolOrFunc.toString().search(/return (true|false);/) !== -1)) {
    // BoolOrFunc is either a boolean or contains a return string with a boolean.
    // Handle it as the intended argument.
}
Run Code Online (Sandbox Code Playgroud)

请注意,上面的代码可能无法正常工作:我实际上并没有为它构建一个测试用例,因为,它似乎非常低效且可能不可靠,我认为这里有人可能有一个更优雅的解决方案来解决我的困境.话虽如此,我想我会把它包括在讨论中.

Mar*_*nst 1

Meshaal 在问题中做出了预测:

"... one will either be a boolean or a function that returns a boolean."
"... first function, if it exists, will always return a boolean."
Run Code Online (Sandbox Code Playgroud)

根据这个预测,该函数不是图灵机,因为我们知道它会返回一些东西。当然,这不能用简单的正则表达式来完成:只会return !0破坏示例。

但是,如果您使用足够智能的解析器来解析function.toString() 的结果,以找到所有可能的返回点,那么问题原则上应该是可以解决的。