考虑这一段代码
function foo(a) {
return function(b) {
return a+b;
}
}
您可以像
var x = foo(2);
var y = x(3); // y == 5
运行此但这可能在你的代码来完成“速记”像
var x = foo(2)(3); // x == 5
,你有
console.log("value a:"+a +" value b:"+b);
(function (a,b){
console.log("value a:"+a +" value b:"+b);
})(20,10)
没有分号,javscript猜测错误,并认为你正在尝试做的
console.log('')(...)
可以使代码以几种方式运行
最小 - 将单个字符添加到代码中
(function(a,b){
console.log("value a:"+a +" value b:"+b); // add this colon
(function (a,b){
console.log("value a:"+a +" value b:"+b)
}(20,10))
})(30,40)
使你的代码更短
(function(a,b){
console.log("value a:"+a +" value b:"+b)
// use different syntax for the inner IIFE
// add a leading !, or +, or various other characters
!function (a,b){
console.log("value a:"+a +" value b:"+b)
}(20,10)
})(30,40)
然而,以避免任何陷阱,把冒号,他们应该是
v----- this one is optional, but may be required depending on preceding code
;(function(a,b){
console.log("value a:"+a +" value b:"+b); // here
(function (a,b){
console.log("value a:"+a +" value b:"+b) // here
}(20,10)); // here
})(30,40); // and here
有时,javascri pt无法猜测为什么要为你分配分号,并且弄错了......正确地使用分号,这种痛苦就会消失......基本上,js将它解释为'console.log('...' )(...)'...因为console.log返回“undefined”,“undefined”不是函数,它会失败...应该有4';'在你的代码中 - 哟没有 –
@JaromandaX不需要4';',只用于'console.log()'就够了。 –
我从来没有说过代码“需要”4,我说**应该是4 ** - 即使你加了两个你说是必要的,JavaScript“假装”另外两个在那里......哦,你可以通过添加一个单一的';' - 或**,通过缩短代码1个字符 –