How to understand Javascript in deep with var scope & closure? [duplicate]

微笑、不失礼 提交于 2019-12-08 10:36:20

问题


I just can't understand why the the a1 = function ?

and where is my value 1 that was passed to the fn(),

whether it was overrwrited by var a ?

the problem look like caused by the same names( var & function) !

function fn(a) {
    console.log("a1 = " + a);
    var a = 2;
    function a() { }
    console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2

function fnx(ax) {
    console.log("a1 = " + ax);
    var ax = 2;
    function b() { }
    console.log("a2 = " + ax);
}
fnx(1);
// a1 = 1
// a2 = 2

/* it equal to the final version */
function fn(a) {
    var a;
    a = function() { }
    // function hoisting > variable hoisting
    console.log("a1 = " + a);
    a = 2;
    console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2

回答1:


I just can't understand why the the a1 = function ?

Function declarations are:

  1. Hoisted to the top of the function they appear in
  2. Declare a local variable (with the same name as the function) in the scope of the function they appear in (this isn't relevant because argument definitions do that too)
  3. Assign themselves as the value of that variable

and where is my value 1 that was passed to the fn(),

Overwritten by the function declaration

whether it was overrwrited by var a ?

The var is ignored because there is already a local variable named a.

The assignment overwrites the function between the two console.log statements.


Your code is effectively the same as:

function fn(a) {
    a = function a() { };
    console.log("a1 = " + a);
    a = 2;
    console.log("a2 = " + a);
}
fn(1);


来源:https://stackoverflow.com/questions/41198746/how-to-understand-javascript-in-deep-with-var-scope-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!