Skip to content

Instantly share code, notes, and snippets.

@ronaldronson
Last active January 3, 2016 13:48
Show Gist options
  • Save ronaldronson/8471481 to your computer and use it in GitHub Desktop.
Save ronaldronson/8471481 to your computer and use it in GitHub Desktop.
Switch function's scope, return new function
function switchScope(fn, params) {
var keys, values;
keys = Object.keys(params);
values = keys.map(function (val) {
return params[val];
});
keys.push("return " + fn);
return Function
.apply(null, keys)
.apply(null, values);
}
var a = 1, b = 2,
add = function () { return a + b },
res1, res2;
res1 = add();
add = switchScope(add, {a: 3, b: 4});
res2 = add();
console.log(res1, res2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment