问题描述:

This question already has an answer here:

  • Javascript : is given function empty?

    6 answers

网友答案:

I think something like this should work:

Assuming you have something like this:

var functions = {
    aFunctionRun: function () {return false;}
    bFunctionRun: function ('foobar') {}
    cFunctionRun: function () {}
}

Try this code:

function isEmpty(function){
    // Get the string from the function;
    var funcString = function.toString();
    // Cut off the part before the actual content of the function
    funcString = funcString.substr(funcString .indexOf(')'))
        .replace(/function|[(){};]/g,'') // remove the function keyword, and the following characters: (){};
        .trim();                         // remove any leading / trailing whitespaces and 
    return funcString === '';            //check if it's an empty string.
}

isEmpty(functions.aFunctionRun); // returns false
isEmpty(functions.bFunctionRun); // returns true
isEmpty(functions.cFunctionRun); // returns true
网友答案:

You can use toString on the function and remove the whitespace to see if the function is empty.

var isEmpty = cFunctionRun.toString().replace(/\s+/g, '') === 'function(){}';
相关阅读:
Top