我正在写一个web应用程序(老实说,我不知道如果没有stackoverflow我会做什么),但这是我正在做的。
我的用户可以定义自定义函数,有人向我指出,应该有一种方法来警告用户该函数为空。
例如,用户可以将他的函数写成如下所示
cFunctionRun: function () {}遗憾的是,我无法控制函数是如何创建的,这意味着这很有可能发生。
所以现在我必须找到一种方法来告诉用户这个函数不会做任何事情,因为它什么也做不了。如果这是不可能的,那也没关系,但我想问问也无伤大雅。
有关cFunctionRun部件的更多信息,请查看此stackOverflow问题jQuery bind custom function to appended element
发布于 2013-02-07 22:51:43
我认为像这样的东西应该是有效的:
假设你有这样的东西:
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-07 22:51:07
您可以在函数上使用toString并删除空格,以查看该函数是否为空。
var isEmpty = cFunctionRun.toString().replace(/\s+/g, '') === 'function(){}';https://stackoverflow.com/questions/14753821
复制相似问题