Skip to content

Instantly share code, notes, and snippets.

@kyrylo
Created December 15, 2013 15:03
Show Gist options
  • Save kyrylo/7974037 to your computer and use it in GitHub Desktop.
Save kyrylo/7974037 to your computer and use it in GitHub Desktop.
JavaScript for entertainment 1. Inspired by freetonik.
/*
* By default, `eval` evaluates code in the current context.
*/
var x = 0;
function foo() {
var x = 5;
eval('x = 100');
return x;
}
x; // 0
foo(); // 100
x; // 0
/*
* However, there's a trick to confuse everyone. If we assign the `eval`
* function to a variable, the function inside that variable "detaches"
* from the current context: `this` becomes the global object.
*/
var x = 0;
function bar() {
var x = 5,
evil = eval;
evil('x = 100');
return x;
}
x; // 0
bar(); // 5
x; // 100
/*
* How you could write such a function (in reality, you shouldn't) to make
* everyone superconfused.
*/
var x = 0;
function bar() {
var x = 5,
evil = eval.call(this, 'eval');
evil('x = 100');
return x;
}
x; // 0
bar(); // 100
x; // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment