I know this may sound a little absurd, but I'm looking for a way to define every variable within a function as a property of this
. I'm looking for any hack, any way possible to be able to have some way to track variables within a function (i.e. add them to the this
object) without having to actually preface every single variable definition with this.
. Is there a way? Is this possible with Proxy
?
function () {
// declare a variable
var hello = 'hi'
return this
}
let {hello} = function()
console.log(hello) // hi
For example this works:
function hi () { this.hello = true; return this }
hi.bind({})() // { hello: true }
What I want is a way to have all variables defined within hi
to be added to the this
object when they are defined.
You can, kind of. But it's a very very dirty hack which requires you to
with
statement, which has performance costs, is bad practice, and is not allowed in strict mode.eval
to get the values of the variables.var
variables are detected, but notlet
orconst
ones.You are looking for the worst hack imaginable? Sure, everything is possible:
The proxy claims to contain all names that could ever be used as a variable in the
with
scope. This basically leads to all assignments of undeclared orvar
-declared variables create properties on the target (unless you uselet
orconst
, they'll be truly local to the block scope).However, for variable lookup everything that is not a target property will be resolved in the global scope (using global
eval
) as the original scope cannot be retained when the proxy said it can deliver all variables.