Are variables statically or dynamically “scoped” in javascript?

前端 未结 7 1909
無奈伤痛
無奈伤痛 2020-12-13 18:38

Or more specific to what I need:

If I call a function from within another function, is it going to pull the variable from within the calling function, or from the le

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 19:19

    I would like to add that lambda expressions are also statically scoped at the location that the expression is defined. For example,

    var myVar = 0;
    
    function foo() {
        var myVar = 10;
        return { bar: function() { addMe = myVar + 10; }}
    }
    
    var myObj = foo();
    
    var addMe = 6;
    alert(addMe);
    
    myVar = 42;
    myObj.bar();
    
    alert(addMe);
    

    This will display 6 and 20.

提交回复
热议问题