首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何判断函数是否为空?

如何判断函数是否为空?
EN

Stack Overflow用户
提问于 2013-02-07 22:44:31
回答 2查看 113关注 0票数 2

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

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

例如,用户可以将他的函数写成如下所示

代码语言:javascript
运行
复制
cFunctionRun: function () {}

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

所以现在我必须找到一种方法来告诉用户这个函数不会做任何事情,因为它什么也做不了。如果这是不可能的,那也没关系,但我想问问也无伤大雅。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-07 22:51:43

我认为像这样的东西应该是有效的:

假设你有这样的东西:

代码语言:javascript
运行
复制
var functions = {
    aFunctionRun: function () {return false;}
    bFunctionRun: function ('foobar') {}
    cFunctionRun: function () {}
}

尝试以下代码:

代码语言:javascript
运行
复制
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
票数 2
EN

Stack Overflow用户

发布于 2013-02-07 22:51:07

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

代码语言:javascript
运行
复制
var isEmpty = cFunctionRun.toString().replace(/\s+/g, '') === 'function(){}';
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14753821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档