Skip to content

Instantly share code, notes, and snippets.

@PsychoLlama
Last active September 13, 2016 18:53
Show Gist options
  • Save PsychoLlama/014bb0f0e8ae2a0359be93693c121816 to your computer and use it in GitHub Desktop.
Save PsychoLlama/014bb0f0e8ae2a0359be93693c121816 to your computer and use it in GitHub Desktop.
Injecting local variables into functions (for people with zero moral boundaries)
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