我试图做一个通用的错误消息函数,我可以在任何JavaScript
函数中使用。这个函数会测试一定的有效性,如果失败,停止调用函数的死锁。如何让我的匿名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'声明绝对没有影响任何事情。 – Pointy
你想抛出错误或返回错误信号值吗? – Bergi
是的,这就是我发现的。大声笑 – cbmeeks