“Uncaught TypeError:undefined不是函数”在JavaScript代码块中 [英] "Uncaught TypeError: undefined is not a function" in JavaScript code block
问题描述
我的html页面中有一个如下所示的JavaScript代码块。当我通过加载页面来运行它。我的浏览器控制台输出低于输出。
I have a JavaScript code block like below in my html page. When I run this by loading the page. I am getting below output on my browser console.
outer world
Uncaught TypeError: undefined is not a function
正如您在代码片段中看到的,我没有执行名为 b的函数
代码中的任何位置。但是在运行代码时,该函数的输出随附 undefined不是函数错误
我找不到我的代码块中的任何位置。
As you can see in the code snippet, I am not executing the function named b
anywhere in the code. But on running the code, the output from that function is coming along with an undefined is not a function error
which I could not locate anywhere in my code block.
要在此方案中添加更多内容,当我删除代码中的任何一个部分时,没有日志。那是。如果我从代码中删除b的初始化,则没有错误和输出。此外,如果我删除自执行功能块,则没有日志或错误。确实b的初始化行缺少分号。但诱惑它提供这样的输出会让我感到困惑。你能帮助我找出这种行为的推理吗?
To add more to this scenario, there is no logs when I remove any one of the parts in the code. that is. If I remove b's initialization from the code then there are no errors and output. Also if I remove the self executing function block, there are no logs or errors. Its true that the b's initialization line is missing a semicolon. but what tempts it to provide such an output confuses me. Would you help me out to figure out a reasoning for this behaviour?
你能帮我理解为什么会这样吗?
Can you please help me understand why it is happening so?
var b = function() {
console.log('outer world');
}
(function() {
})();
推荐答案
在声明 b
后错过了;
。以下代码与您拥有的代码相同。
Missed a ;
after declaring b
. The following code is equivalent to what you have.
var b = function() {
console.log ('outer world');
}(function() {})();
没有;
b变为自动执行并将一个空函数作为参数。之后它再次自我执行;但是,因为b没有返回函数,你会得到一个例外。
Without the ;
b becomes self-executing and takes an empty function as a parameter. After that it self-executes again; however, because b does not return a function, you get an exception.
我建议不要跳过;
直到你成为js忍者:)。保留 b
以避免全球范围内的污染。
I suggest not to skip ;
until you become js ninja :). Keep b
inside to avoid global scope pollution.
(function () {
"use strict";
var b = function () {
console.log("hi");
};
// other code
}());
如果你不想要分号,添加自运行函数之前的运算符
In case you do not want semicolons, add an operator before self-running function
var b = function () { console.log('outer world') }
;(function() { /* ... */ }())
ES6更新:
(() => {
const b = () => console.log('hi')
// ...
})()
这篇关于“Uncaught TypeError:undefined不是函数”在JavaScript代码块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!