[英]Immediately invoked function expression causing error?
Can someone explain why this could happen? 有人可以解释为什么会发生这种情况吗?
If I write something like this in a file named like test.js
, 如果我在名为
test.js
的文件中编写类似的test.js
,
const anyObject = {}
(function(){
console.log('hello world!')
}())
run it through console with $node test.js
使用
$node test.js
通过控制台运行它
then in the console, a hello world!
然后在控制台中,
hello world!
will be printed, but followed with this: TypeError: (intermediate value) is not a function
将被打印,但随后显示:
TypeError: (intermediate value) is not a function
Idon't know what exactly happend there, I guess somehow node is taking the function expression as a function call expression ? 我不知道那里到底发生了什么,我想节点会以某种方式将函数表达式作为函数调用表达式?
I'm using node v6.9.1
我正在使用节点
v6.9.1
You could use void
for calling without semicolon. 您可以在没有分号的情况下使用
void
进行呼叫。
This forces the expression to evaluate and return undefined
. 这将强制表达式求值并返回
undefined
。
const anyObject = {} void (function() { console.log('hello world!') }())
It works even without outer parenthesis. 即使没有外部括号也可以使用。
const anyObject = {} void function() { console.log('hello world!') }()
const anyObject = {}; (function(){ console.log('hello world!'); })();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.