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?
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?
Share Improve this question edited Apr 19, 2019 at 0:27 Miroslav Glamuzina 4,5872 gold badges21 silver badges33 bronze badges asked Apr 18, 2019 at 23:52 Some GuySome Guy 13.6k22 gold badges62 silver badges93 bronze badges 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. – Khauri 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. – Thomas Commented Apr 19, 2019 at 0:40
3 Answers
Reset to default 4No, 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();
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();
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) }
}