javascriptclosures

Is it possible to change variables inside a closure in JavaScript?


Let's suppose I have the following:

(function() {
  let myVar = 300;
  window.myFunc = function() {
    console.log(myVar);
  };
})();

Without changing the above code, can you think of a way to change the myVar variable? I mean from the outside, can you do something like:

window.myFunc.__closure__.myVar = 10;

Is this possible?


Solution

  • No, it is not possible because the scope of the variable is the function's block.

    The only way of modifying something inside of the closure is thru properties in the current lexical context (in this case the window object).

    (function() {
      this.myVar = this.myVar || 300;
      window.myFunc = function() {
        console.log(myVar);
      };
    })();
    
    myVar = "Ele";
    myFunc();