Javascript Self Executing supposed to work?

前端 未结 2 724
梦谈多话
梦谈多话 2021-01-06 06:59

I had this code :

function (i)
{
    alert(i);
}(3);

And it wasn\'t working , So After StackOverFlow Question - I changed it to :

2条回答
  •  遥遥无期
    2021-01-06 07:22

    The compiler needs to differentiate between function declaration statement and function definition expression. You can only call functions in expressions.

    When the keyword function appears after '=' or '(' the compiler knows this must be a function definition expression (since only expressions and not statements are allowed after '=' or '(') and allows you to call it immediately. When the keyword function starts a new statement the compiler assumes it to be a function declaration statement and hence you can't call the function immediately.

    Note that function declaration statement requires you to name the function. This allows you to call it later. You may omit the function name in function definition expressions (and you can call them immediately).

    Edited

    all the bold fonts were made by Royi Namir the OP: those bold words are the key for understanding.

    this is the most logical Explanation after a lot of tests.
    

    See This

    http://jsbin.com/imetan/edit#javascript,html

提交回复
热议问题