Last active
February 25, 2019 22:37
-
-
Save joshuaaguilar20/96870d4ac990d89841fc3a0b0c6f84cc to your computer and use it in GitHub Desktop.
Closure Cheats( Do Not Use) CH-2
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
function foo(str) { | |
"use strict"; | |
eval( str ); | |
console.log( a ); // ReferenceError: a is not defined | |
} | |
foo( "var a = 2" ); | |
` There are other facilities in JavaScript that amount to a very similar | |
effect to eval(..) . setTimeout(..) and setInterval(..) can take a | |
string for their respective first argument, the contents of which are | |
eval uated as the code of a dynamically generated function. This is old, | |
legacy behavior and long-since deprecated. Don’t do it! | |
The new Function(..) function constructor similarly takes a string | |
of code in its last argument to turn into a dynamically generated func‐ | |
tion (the first argument(s), if any, are the named parameters for the | |
new function). This function-constructor syntax is slightly safer than | |
eval(..) , but it should still be avoided in your code. | |
The use-cases for dynamically generating code inside your program | |
are incredibly rare, as the performance degradations are almost never | |
worth the capability. | |
with | |
The other frowned-upon (and now deprecated!) feature in JavaScript | |
that cheats lexical scope is the with keyword. There are multiple valid | |
ways that with can be explained, but I will choose here to explain it | |
from the perspective of how it interacts with and affects lexical scope. | |
with is typically explained as a shorthand for making multiple prop‐ | |
erty references against an object without repeating the object reference | |
itself each time. | |
` | |
For example: | |
var obj = { | |
a: 1, | |
b: 2, | |
18 | |
}; | |
// more | |
obj.a = 2 | |
obj.b = 3 | |
obj.c = 4 | |
"tedious" to repeat "obj" | |
// "easier" short-hand | |
with (obj) { | |
a = 3; | |
b = 4; | |
c = 5; | |
} | |
function foo(obj) { | |
with (obj) { | |
a = 2; | |
} | |
} | |
var o1 = { | |
a: 3 | |
}; | |
var o2 = { | |
b: 3 | |
}; | |
foo( o1 ); | |
console.log( o1.a ); // 2 | |
foo( o2 ); | |
console.log( o2.a ); // undefined | |
console.log( a ); // 2—Oops, leaked global! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment