[removed] is given function empty?

后端 未结 6 1814
日久生厌
日久生厌 2020-12-03 07:50

Let\'s have a function call

function doSomethingAndInvokeCallback(callback){
    // do something
    callback();
}

I can check if given arg

6条回答
  •  孤街浪徒
    2020-12-03 08:04

    One possibility is matching the .toString result against a regexp to get the function body, and then trim to check whether it has become an empty string:

    var f = function foo()    { 
    
    
    };
    
    /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
         f.toString().replace(/\n/g, "")
    )[1].trim() === ""; // true
    

    That ugly regexp does take care of spaces aroung named functions as well as extraneous spaces before the name and the opening brace. Spaces like in foo () do seem to be removed, so there is no reason to check for those.

提交回复
热议问题