【发布时间】:2014-01-21 19:55:31
【问题描述】:
我正在尝试制作一个可以在任何JavaScript 函数中使用的通用错误消息函数。该函数将测试某些有效性并在调用函数失败时停止调用函数。
例如:
var fun = function() {
var a = {};
a.blah = 'Hello';
checkIfExistErrorIfNot(a); // fine, continue on...
checkIfExistErrorIfNot(a.blah); // fine, continue on...
checkIfExistErrorIfNot(a.notDefined); // error. stop calling method ("fun") from continuing
console.log('Yeah! You made it here!');
}
这是我第一次尝试:
var checkIfExistErrorIfNot(obj) {
var msg = 'Object does not exist.';
if(!obj) {
return (function() {
console.log(msg);
return false;
})();
}
return true;
}
返回的匿名函数执行得很好。但调用函数仍在继续。我猜是因为 anon 函数没有在调用函数的范围内执行。
谢谢。
编辑
我可能没有明确表达我的意图。以下是我通常在我的方法中所做的:
saveData: function() {
var store = this.getStore();
var someObj = this.getOtherObject();
if(!store || !someObj) {
showError('There was an error');
return false; // now, 'saveData' will not continue
}
// continue on with save....
}
这是我想做的:
saveData: function() {
var store = this.getStore();
var someObj = this.getOtherObject();
checkIfExistErrorIfNot(store);
checkIfExistErrorIfNot(someObj);
// continue on with save....
}
现在,更酷的是:
...
checkIfExistErrorIfNot( [store, someObj] );
...
并遍历数组...取消未定义的第一个项目。但如果我能找到如何让第一部分工作,我可以添加数组片段。
谢谢
【问题讨论】:
-
您正在调用“checkIfExistErrorIfNot”并丢弃返回值。因此,该函数中的
return语句对任何内容都没有任何影响。 -
您想
throw一个错误还是return一个错误信号值? -
是的,这就是我发现的。大声笑
-
@Bergi 我真正想做的是停止执行调用函数(在这个例子中是“有趣”)。原因是我的一些函数会加载数据存储、数组等。而且到处都有大量的
if(datastore) {....开始看起来很难看。我有时会在顶部放一个if(!datastore) {..exit..}。这很好。但我只是在寻找一种更清洁(如“更漂亮”)的方式来做到这一点。 -
@cbmeeks:嗯,你可以通过两种方式停止函数:引发异常或提前返回。
标签: javascript scope anonymous-function