Created
December 15, 2013 15:03
-
-
Save kyrylo/7974037 to your computer and use it in GitHub Desktop.
JavaScript for entertainment 1. Inspired by freetonik.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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