search

Home  >  Q&A  >  body text

javascript - js scope problem?

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_u1582phpcn_u15822718 days ago655

reply all(4)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:52:34

    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.

    reply
    0
  • 阿神

    阿神2017-06-26 10:52:34

    @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.

    reply
    0
  • 欧阳克

    欧阳克2017-06-26 10:52:34

    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在自执行函数那里没有获取到返回值

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:52:34

    reply
    0
  • Cancelreply