[removed] is given function empty?

后端 未结 6 1802
日久生厌
日久生厌 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:13

    You might be able to get this from .toString():

    var blank = function(){};
    var f = function(){};
    var f2 = function() { return 1; };
    
    f.toString() == blank.toString(); // true
    f2.toString() == blank.toString(); // false
    

    but this is really prone to error:

    var blank = function(){};
    var f = function(){ }; // extra space!
    f.toString() == blank.toString(); // false
    

    You could munge the strings a bit to try to overcome this, but I suspect this is very browser-dependent. I wouldn't actually try to do this in a production environment if I were you. Even if you normalize the whitespace, it still won't catch other no-op lines, including comments, useless var statements, etc. To actually address these issues, you'd probably need a whole tokenizer system (or a crazy regex).

提交回复
热议问题