Kevin Meredith
Kevin Meredith

Reputation: 41939

Variable Scope in Closure

In the following code (from Secrets of the JavaScript Ninja), I don't understand why inner | tooLate prints out ronin. I would've expected undefined.

var outerValue = "ninja";
var later;

function outerFunction() {
    var innerValue = "samurai";

    function innerFunction(paramValue) {
        console.log("outerValue:",outerValue);
        console.log("innerValue:",innerValue);
        console.log("paramValue:",paramValue);
        console.log("inner | tooLate", tooLate);
    }
    later = innerFunction;
}

console.log("outer | tooLate", tooLate);

var tooLate = "ronin";

outerFunction();
later("warrior");

My confusion is how tooLate is accessible within innerFunction. Isn't innerFunction's scope limited to outerFunction?

http://jsfiddle.net/6HuaS/

Upvotes: 1

Views: 55

Answers (1)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94409

innerFunction is under outerFunction which is under window, therefore innerFunction can access all properties and methods of window.

In your example, tooLate is declared under the window scope (global). Since you haven't declare a new tooLate in outerFunction nor innerFunction, it will trace back all the way to window to find a declared tooLate.

var b, val = 0;
function a(){
    b = function (){
        console.log(val);
    }
}
a();
val = 2;
b();  //2
Scope:

window
├─ a: function
│ └─ b: function      b can access variables in a, b, and all the way to window
└─ val: number         if the variable name hasn't been overridden

Upvotes: 3

Related Questions