7

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?

2
  • 1
    Is there a reason you want to do this? Or are you just curious if it's possible. Without modifying the code the answer is no. Or at least, you shouldn't be able to. Commented Apr 19, 2019 at 0:11
  • via Dev-tools; just set a break point in any function that can see this variable. via code, No, not possible, not without changing the code; unless they use evil() somewhere where this variable is visible, and you can inject some code. Commented Apr 19, 2019 at 0:40

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

@Ele Yeah I should have taken a little more time to read the question before answering.
The code here is solid, but the explanation a little lacking. setMyVar closes over the same variables as myFunc, so can change them. ES modules more or less work the same way.
Quite related to your answer stackoverflow.com/questions/2497801/… And MDN has a half-page on this too developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
1

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) }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.