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"); |
This isn't guaranteed to work. It depends on what the foo
function is doing. For example, replacing foo
with:
function foo(msg) {
setTimeout(function () {
console.log(msg + ": " + g);
}, 0);
}
gives me:
not hacked: 3
not hacked again: 3
hacked: 3
because g
has been reset before the console.log
statement accesses it.
https://gist.github.com/2862221
That's the only solution I could think of now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: