Last active
September 13, 2016 18:53
-
-
Save PsychoLlama/014bb0f0e8ae2a0359be93693c121816 to your computer and use it in GitHub Desktop.
Injecting local variables into functions (for people with zero moral boundaries)
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
Function.prototype.with = function () { | |
// No local variables are defined to prevent scope pollution, | |
// cuz `eval` can see 'em. | |
// `with` turns object properties into local variables. | |
with (arguments[0] || {}) { | |
// Turn the function into a string, then eval it as an expression. | |
return eval(`(${String(this)})`).call( | |
// Invoke it and apply the `this` and `arguments` params. | |
...([].slice.call(arguments).slice(1)) | |
) | |
} | |
} | |
/* | |
(function () { | |
console.log(local) // Scoped data! Yeah! | |
}).with({ local: 'Scoped data! Yeah!', fired: 'probably' }) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment