2以下自调用功能不起作用

时间:2011-12-15 17:08:22

标签: javascript self-invoking-function

这段代码有什么问题?

function test() {

   (function(){
      console.log('1')  
   })()

   (function(){
      console.log('2')
   })()
}

test()

http://jsfiddle.net/VvaCX/

2 个答案:

答案 0 :(得分:8)

你错过了每个函数调用结束时的分号......

function test() {

    (function(){
        console.log('1');  
    })();

    (function(){
        console.log('2');
    })();
}

test();

Here is a JSFiddle工作代码,如果您需要测试它。例如,在Chrome中,您可以右键单击>检查元素>并切换到“控制台”选项卡

感谢@pimvdb指出当你没有分号时实际上会尝试做什么:

  

目前正在尝试将第二个函数作为参数传递给第一个函数。

答案 1 :(得分:2)

我刚刚测试过。你需要你的分号。

这有效:

function test() {

    (function(){
        console.log('1');
    })()

    (function(){
        console.log('2');
    })()
}

test()

Firebug在console.log('1')

显示错误