var b = 10;
(function b(){
b = 20;
console.log(b);
})();
Why does the result output the function? I also want to ask if the b
function in the brackets has function promotion
The function name in the function expression is immutable and can only be quoted and cannot be assigned. If you add 'use strict'
you can observe the error in strict mode.
@Light key quick code 10 needs to be followed by a semicolon
There is no function promotion here. Function promotion only exists in the case of "function declaration", not in the case of "function expression".
Regarding the difference between "function declaration" and "function expression", many articles on the Internet explain it very clearly. You can search and learn by yourself.
What the second floor said is that it is not possible to modify the function name in a function, for example:
(function a(){
a = 10; //這個(gè)表達(dá)式不會(huì)成功,函數(shù)a依舊是函數(shù)a,至于這里面的a = 10等同于被廢棄了,也不會(huì)生成相應(yīng)的全局變量
})();
As for why function a is output instead of 20, the simple point is that the statement is directly skipped, which is equivalent to
var b = 10;
(function b(){
console.log(b);
})();
Supplement:
I was just reminded that self-executing functions are also function expressions. I apologize for misleading you when I started writing the answer.
var b = 10;
var b = (function(){
b = 10;
console.log(b); //輸出:10
})();
console.log(b); //輸出:undefined 。 b在自執(zhí)行函數(shù)那里沒(méi)有獲取到返回值