Is it possible to somehow pass the scope of a function to another?
For example,
function a(){
var x = 5;
var obj = {..};
b(<my-scope>);
}
function b(){
//access x or obj....
}
I would rather access the variables directly, i.e., not using anything like this.a or this.obj, but just use x or obj directly.
The only way to truly get access to function
a‘s private scope is to declarebinside ofaso it forms a closure that allows implicit access toa‘s variables.Here are some options for you.
Direct Access
Declare
binside ofa.If you don’t want
binside ofa, then you could have them both inside a larger container scope:These are the only ways you’re going to be able to use
a‘s variables directly inbwithout some extra code to move things around. If you are content with a little bit of “help” and/or indirection, here are a few more ideas.Indirect Access
You can just pass the variables as parameters, but won’t have write access except to properties of objects:
As a variation on this you could get write access by passing updated values back to
alike so:You could pass
ban object with getters and setters that can accessa‘s private variables:The getters and setters could be public, assigned to the
thisobject ofa, but this way they are only accessible if explicitly given out from withina.And you could put your variables in an object and pass the object around:
As a variation you can construct the object at call time instead: