javascript - 当代码中有另一个不相关的函数时出现“不是函数”错误
问题描述
我有两段代码,每段代码都按预期工作:
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);
超时似乎解决了它的事实让我认为它与一些异步的东西有关,但我无法准确解释它为什么会发生。
解决方案
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.
推荐阅读
- speech-to-text - Tizen TV Xamarin 语音转文本(无可用引擎例外)
- python - 使用 Bron–Kerbosch 找到单个最大集团
- javascript - 在抽出的卡片上定义一个数字
- c# - C# regedit 写入失败
- linux - 文件内容更改时是否存在某种类型的硬链接中断
- javascript - Body 元素上的 Vue JS 样式绑定
- sql-server - 获取每个purchaseorderdetail id Adventureworks的供应商ID
- python - 删除数据框中文本上的 b''(编码结果)
- javascript - 如何在打字稿中获取模板类型的类型名称?
- delphi - 选择标识符时,查找在 IDE 中不起作用的引用