【问题标题】:How can I get my anonymous JavaScript function to execute withing the calling scope?如何让我的匿名 JavaScript 函数在调用范围内执行?
【发布时间】: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


【解决方案1】:

您可以为此使用例外:

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());

【讨论】:

  • 添加异常肯定可以。我在其他领域也做类似的事情。但我们的想法是甚至不使用 try/catch(或包装它),这样“有趣”就只有一行。
猜你喜欢
  • 2011-02-13
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2012-10-12
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
相关资源
最近更新 更多