public
Last active

A JavaScript "eval is evil" narrative by way of the "pass a string to setTimeout" anti-pattern...

  • Download Gist
eval-is-evil.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// 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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.