Patrick Roberts Patrick Roberts - 4 months ago 8
Javascript Question

Is there a method for accessing variables in the parent scopes of a function

Given a reference to a

function
, is it possible to access the variable names and/or values in its parent scopes? For example:



let ref = (function myClosure() {
const foo = 'foo';
const bar = 'bar';

return {
sneaky() {
// use the variables somehow
// since some browsers optimize functions
// by omitting parent scopes from the context
// that are not used
console.log(foo, bar);
}
};
}());

// given `ref.sneaky` in this scope, how to access the scope in `myClosure`?
console.log(ref);





Inspecting
ref
in the developer console, we find this:

inspection of <code>ref</code>

Notice the
Closure
object which contains
foo
and
bar
. If it is not possible to obtain this closure object programmatically, is there any currently proposed ECMAScript standard like say,
Symbol.scope
that could contain the array of parent "closure objects" of a given function?

Update



To address @Bergi and @Oriol's comments, I'm adding some clarification.



let ref = (function myClosure() {
const foo = 'foo';
const bar = 'bar';

return {
sneaky(...variableNames) {
// use the variables somehow
// since some browsers optimize functions
// by omitting parent scopes from the context
// that are not used
console.log(foo, bar);

return Object.assign(...variableNames.map(variableName => ({
[variableName]: eval(variableName)
})
));
}
};
}());

// given `ref.sneaky` in this scope, how to access the scope in `myClosure`?
console.log(ref.sneaky('foo', 'bar'));





Sure, this works if the variable names are known ahead of time, and if an
eval
exists in the child scope, but what if neither of these conditions are met?

Answer

Given a reference to a function, is it possible to programmatically access the variable names and/or values in its parent scopes?

No.

Is there any currently proposed ECMAScript standard like say, Symbol.scope that could contain the array of parent "closure objects" of a given function?

No. And if there was, it would never get accepted, as closures are the only means of true encapsulation in javacript, and introducing such an accessor would be a gaping security hole (for references, see http://www.ieee-security.org/TC/SP2011/PAPERS/2011/paper023.pdf or http://web.emn.fr/x-info/sudholt/papers/miss13.pdf).

Comments