Skip to content

Instantly share code, notes, and snippets.

@drcircuit
Created September 27, 2017 21:55
Show Gist options
  • Select an option

  • Save drcircuit/4722a2e5c4ce5a8ae6f5d77eaecf0053 to your computer and use it in GitHub Desktop.

Select an option

Save drcircuit/4722a2e5c4ce5a8ae6f5d77eaecf0053 to your computer and use it in GitHub Desktop.
The evil that is "this"
//this is how we are taught to encapsulate in JavaScript, should be safe right?
function list(){
var protectedArray = [];
return {
append: function(val){
protectedArray.push(val);
},
store: function(idx, val){
protectedArray[idx] = val;
},
get: function(idx){
return protectedArray[idx];
}
}
}
stuff = list();
stuff.append(7);
stuff.store(1,8);
console.log(stuff.get(0)); // 7
console.log(stuff.get(1)); // 8;
// Seems ok... but there is some quirkyness of this language going on that we can xploit!
// store a function that when called sets the global stolenArray to reference the "this" reference once called.
var stolenArray;
stuff.store('push', function(){
stolenArray = this;
});
// all we need to do make that happen, is to get that function called - lucky for us, we have a method that will do that for us..
stuff.append();
console.log(stolenArray); // is now protectedArray!!
stuff.append(10); //doesn't work anymore...
stolenArray[10] = 'some bad value that enables bad things..';
console.log(stuff.get(10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment