Skip to content

Instantly share code, notes, and snippets.

@bjouhier
Created June 2, 2012 12:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bjouhier/2858099 to your computer and use it in GitHub Desktop.
Save bjouhier/2858099 to your computer and use it in GitHub Desktop.
Wrapping a function to hack a global temporarily
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");
@bjouhier
Copy link
Author

bjouhier commented Jun 2, 2012

Output:

not hacked: 3
hacked: 5
not hacked again: 3

@mfncooper
Copy link

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.

@hongymagic
Copy link

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