【问题标题】:JS: Callback is not a function inside if else statementJS:回调不是 if else 语句中的函数
【发布时间】:2019-07-03 19:04:26
【问题描述】:

使用 google chrome 编译时,函数的 else 语句中无法识别回调。尝试运行以下代码时,我的 site.js 文件出现错误:

function changeSetting(callback) {
    var testswitch = document.getElementById("switch");
    if (testswitch.checked) {
        $.ajax({
            type: 'GET',
            url: '/api/ct/off/changeSetting',
            cache: false,
            error: function (jqXHR, textStatus, errorThrown) {
            },
            success: function (result) {
                //No error here
                callback();
            }
        });
    }
    else if (!testswitch.checked) {
        $.ajax({
            type: 'GET',
            url: '/api/ct/on/changeSetting',
            cache: false,
            error: function (jqXHR, textStatus, errorThrown) {
            },
            success: function (result) {
                //ERROR: Callback is not recognized as a function
                callback();
            }
        });
    } else {
        return;
    }
}

这个函数被调用的唯一实例是

changeSetting(displayEmail());

未捕获的类型错误:回调不是函数

【问题讨论】:

  • 我想调用回调函数。删除 () 也不起作用。

标签: javascript ajax google-chrome callback


【解决方案1】:

问题在于你的函数调用。

<script>
function changeSetting(callback) {
....
}

function displayEmail() {
  return "email displayed"; // dummy value in this case 
}
</script>

想象一下运行这段代码。

changeSetting(displayEmail()); // first the display email function is evaluated

请注意,我们正在调用带有括号()displayEmail() 函数。这意味着我们将运行它并取回它的 return 值,无论它是未定义的,还是在我们的例子中为 "email displayed"

在评估作为回调传递的函数后,它会简化为不是函数的东西,因此会出现错误。伪方面,它会“简化”到这一点。

changeSetting("email displayed"); // "email displayed" is obviously not a function

要解决这个问题,首先不要调用函数,将指针传递给函数,即displayEmail

changeSetting(displayEmail);

【讨论】:

  • 如果我有一个三链的回调函数呢? ``` changeSetting(function () { changeTemp(displayEmail); });``` 这样做也会引发错误
【解决方案2】:

只传递 displayEmail 而不是在 changeSetting 函数的参数中调用它

changeSetting(displayEmail);

【讨论】:

    最近更新 更多