Some Guy
Some Guy

Reputation: 13568

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?

Upvotes: 7

Views: 4443

Answers (3)

DarkPurple141
DarkPurple141

Reputation: 290

The idea of using a closure is to make variable accessible only to a specific scope. If you then want to change it outside of this scope, why not use a class?

eg.

class myClass {
  constructor(var) { this._var = var }
  set var(arg) { this._var = arg }

  yourFunc() { console.log(this._var) }
}

Upvotes: 1

Ele
Ele

Reputation: 33726

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();

Upvotes: 4

SimpleJ
SimpleJ

Reputation: 14768

You could define a global function that changes the variable:

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

myFunc();
setMyVar(10);
myFunc();

Or you could return setMyVar:

const setMyVar = (function() {
  let myVar = 300;
  window.myFunc = function() {
    console.log(myVar);
  };
  return value => {
    myVar = value;
  };
})();

myFunc();
setMyVar(100);
myFunc();

Upvotes: 2

Related Questions