Why do we put '(' before fucntion in JS?
This question already has an answer here:
Try not to:
function() { return 1; }()
then you will get Uncaught SyntaxError: Unexpected token (
JavaScript parser runs in two modes, lets call it expression mode and normal mode, in normal mode JS parser expects top level declarations like functions and code blocks. You use '(' to enter expression mode, in expression mode function() { }
will be interpreted as constant whose value is a function.
There is similar case with objects literals:
{ foo: 1 }
without '(' this means block of code, where you have single expression - constant 1 proceeded by label, when you use ({ foo: 1 })
parser enters expression mode and interprets it as object literal with property foo
.
Why two modes, it is enforced by language grammar which in case of JS is pretty complicated (like in most C based languages).
链接地址: http://www.djcxy.com/p/94944.html上一篇: 在JavaScript中定义本地函数:使用var还是不使用?
下一篇: 为什么我们在JS中添加'(')之前?