Created
June 2, 2012 12:18
-
-
Save bjouhier/2858099 to your computer and use it in GitHub Desktop.
Wrapping a function to hack a global temporarily
This file contains 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
var g = 3; | |
function hackGlobal(fn) { | |
return function() { | |
var saveG = g; | |
try { | |
g = 5; | |
fn.apply(this, arguments); | |
} finally { | |
g = saveG; | |
} | |
} | |
} | |
function foo(msg) { | |
console.log(msg + ": " + g); | |
} | |
var bar = hackGlobal(foo); | |
foo("not hacked"); | |
bar("hacked"); | |
foo("not hacked again"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't guaranteed to work. It depends on what the
foo
function is doing. For example, replacingfoo
with:gives me:
because
g
has been reset before theconsole.log
statement accesses it.