Closures And Prototype Chain Attacks
Object.defineProperty(Object.prototype, 'showYourSelf', { get() { return this; } });` allows accessing closure variables safely.
I've always thought that closures were a way to implement private variables, but today I discovered that variables within a closure can be modified, which took me by surprise!
let obj = (function () {
let a = {
x: 1,
y: 2,
};
return {
getKey(key) {
return a[key];
},
};
})();
console.log(obj.getKey('x'));
// 1
Here, 'a' is a variable within the closure, and I only exposed the getKey method. However, I can still access and modify the value of 'a'.
If I want to modify the value of 'a', I definitely can't follow...