Javascript closure / variable scope question - I k

2019-07-07 01:22发布

问题:

I've been developing with JS for a while, and while I know that code below works, I don't really understand why it works.

The way I see it, I've defined testString in testClosure function, and I'm expecting that variable to 'go away' when testClosure function is done, since it's local variable.

However, when I call inner function with a timer, it's still aware of testString variable. Why? Isn't that variable gone five seconds ago when testClosure finished executing? Does the inner function get reference to all variables within testClosure, and they stay valid until all inner functions are done?

function testClosure() {
  var testString = 'hai';

  // after 5 seconds, call function below
  window.setTimeout(function() {

    // check if function knows about testString       
    alert(testString);

  }, 5000);         
}

testClosure();

回答1:

The function special form creates lexical scope. Any object created within that scope will see the environment (the binding of names to values) lexically in scope at the time of its creation.

Indeed, creating a function is the only way to create lexical scope in JavaScript, which is why you see contortions like this all the time:

return (function() {
    var privateVariable = 'foo';
    return {
        myProp: privateVariable
    };
})();


回答2:

In a word, yes. Spot on.



回答3:

testString exists within the scope of testClosure, and therefor the testString is a global variable so far as your timer is concerned.

How do JavaScript closures work?

has better answers, as scott mentions.