Last active
June 22, 2026 01:37
-
-
Save cowboy/5860393 to your computer and use it in GitHub Desktop.
A JavaScript "eval is evil" narrative by way of the "pass a string to setTimeout" anti-pattern...
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
| // An object with a property and a method. | |
| var obj = { | |
| name: "Ben", | |
| logName: function() { | |
| console.log(this.name); | |
| } | |
| }; | |
| // And another global variable, for good measure. | |
| var name = "Whoops"; | |
| // Even though this works great... | |
| obj.logName(); // logs "Ben" | |
| // This doesn't, because of how JavaScript determines the "this" value... | |
| setTimeout(obj.logName, 1000); // logs "Whoops" in one second. | |
| // Someone who doesn't really understand JavaScript might fall back on eval... | |
| setTimeout("obj.logName();", 1000); // logs "Ben" in one second. | |
| // When they should instead be either doing this... | |
| setTimeout(function() { | |
| obj.logName(); | |
| }, 1000); // logs "Ben" in one second. | |
| // Or, in environments that support ES5, this. | |
| setTimeout(obj.logName.bind(obj), 1000); // logs "Ben" in one second. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The example clearly shows how the this context can behave unexpectedly and why better solutions, such as anonymous functions or bind(), should be used. When I learn concepts like these, it reminds me of Slope Rider, where success depends on understanding the mechanics instead of taking risky shortcuts. I believe that mastering these core programming principles leads to cleaner, safer, and more maintainable code.