Javascript / scope variable closing issue - I know this works, but why?

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

As I see it, I defined testString in the testClosure function, and I expect this variable to "go away" when the testClosure function is executed, since it is a local variable.

However, when I call the internal function with a timer, it still knows the testString variable. What for? Didn't this variable disappear five seconds ago when testClosure completed execution? Does an internal function affect all variables in testClosure, and they remain valid until all internal functions are executed?

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

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

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

  }, 5000);         
}

testClosure();
+3
3

function . , , ( ) .

, - JavaScript, :

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

, . .

+2

testString testClosure, testString , .

JavaScript?

, .

0

Source: https://habr.com/ru/post/1723393/


All Articles