2014-01-21 35 views
0

我试图做一个通用的错误消息函数,我可以在任何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]); 
... 

并遍历数组...取消未定义的第一个项目。但是如果我能找到如何让第一部分工作,我可以添加数组片。

感谢

+0

你打电话“checkIfExistErrorIfNot”和*扔掉的返回值*因此,在该功能的'return'声明绝对没有影响任何事情。 – Pointy

+0

你想抛出错误或返回错误信号值吗? – Bergi

+0

是的,这就是我发现的。大声笑 – cbmeeks

回答

0

您可以使用例外是:

var checkIfExistErrorIfNot = function (obj) { 
    var msg = 'Object does not exist.'; 

    if(!obj) { 
     throw new Error(msg); 
    } 
} 

var fun = function() { 
    var a = {}; 
    a.blah = 'Hello'; 

    try { 
     console.log('a:'); 
     checkIfExistErrorIfNot(a);   // fine, continue on... 
     console.log('a.blah:'); 
     checkIfExistErrorIfNot(a.blah); // fine, continue on... 
     console.log('a.notDefined:'); 
     checkIfExistErrorIfNot(a.notDefined); // error. stop calling method ("fun") from continuing 
    } catch (e) { 
     return false; 
    } 

    console.log('Yeah! You made it here!'); 
    return true; 
} 

console.log(fun()); 
+0

添加例外肯定会做到这一点。我在其他领域做了类似的事情。但是这个想法是甚至不使用try/catch(或者包装它),这样“fun”就只有一行。 – cbmeeks