javascript - js scope problem?
phpcn_u1582
phpcn_u1582 2017-06-26 10:50:34
0
4
648
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

phpcn_u1582
phpcn_u1582

reply all(4)
扔个三星炸死你

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; //这个表达式不会成功,函数a依旧是函数a,至于这里面的a = 10等同于被废弃了,也不会生成相应的全局变量
})();

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在自执行函数那里没有获取到返回值
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template