首页 > 解决方案 > 当代码中有另一个不相关的函数时出现“不是函数”错误

问题描述

我有两段代码,每段代码都按预期工作:

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)

function Test() {}

(function() {
    console.log(this)
}).call(Test)

它们都产生预期的输出:[Function: Test].

但是,当这些独立的代码片段组合在一起时,就会产生错误。因此,运行以下代码

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)

(function() {
    console.log(this)
}).call(Test)

结果是

TypeError: tmp.call(...) is not a function

我为此找到了一个不优雅的解决方案,它增加了第二个代码片段的延迟。因此,以下将产生所需的输出([Function: Test]两次):

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)

setTimeout(() => {
    (function() {
        console.log(this)
    }).call(Test)
}, 100);

超时似乎解决了它的事实让我认为它与一些异步的东西有关,但我无法准确解释它为什么会发生。

标签: javascriptthisanonymous-function

解决方案


You're falling victim to an automatic semicolon insertion trap. The code

tmp.call(Test)

(function() {
    console.log(this)
}).call(Test)

is interpreted as if it were written

tmp.call(Test)(function() { console.log(this) }).call(Test)

If a semicolon is introduced:

tmp.call(Test);

(function() {
    console.log(this)
}).call(Test)

then it will work.

The precise rules involve some "legalese" that's somewhat hard to digest, but the basic idea (in this case) is that a semicolon won't be inserted when an expression can syntactically work when the newline is considered to be a simple space character.


推荐阅读