2

我正在编写一个网络应用程序(老实说,我不知道如果没有 stackoverflow 我会做什么),但这就是我正在做的事情。

我的用户可以定义自定义函数,马上有人向我指出应该有一种方法来警告用户该函数是空白的。

例如,用户可以编写他的函数看起来像这样

cFunctionRun: function () {}

可悲的是,我无法控制如何创建函数,这意味着这很可能会发生。

所以现在我必须想办法告诉用户这个函数不会做任何事情,因为它什么也做不了。如果这是不可能的,那很好,但我认为问它不会有什么坏处。

有关 cFunctionRun 部分的更多信息,请查看这个 stackOverflow 问题jQuery bind custom function to appended element

4

2 回答 2

2

我认为这样的事情应该有效:

假设你有这样的事情:

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

试试这个代码:

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
于 2013-02-07T14:51:42.920 回答
0

您可以toString在函数上使用并删除空格以查看函数是否为空。

var isEmpty = cFunctionRun.toString().replace(/\s+/g, '') === 'function(){}';
于 2013-02-07T14:51:06.837 回答