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.
No.
You're accessing the local scope object. The
[[Context]]
.You cannot publicly access it.
Now since it's node.js you should be able to write a C++ plugin that gives you access to the
[[Context]]
object. I highly recommend against this as it brings proprietary extensions to the JavaScript language.The only way to truly get access to function
a
's private scope is to declareb
inside ofa
so it forms a closure that allows implicit access toa
's variables.Here are some options for you.
Direct Access
Declare
b
inside ofa
.If you don't want
b
inside 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 inb
without 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
a
like so:You could pass
b
an object with getters and setters that can accessa
's private variables:The getters and setters could be public, assigned to the
this
object 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:
Have you tried something like this:
If you can stand function B as a method function A then do this:
As others have said, you cannot pass scope like that. You can however scope variables properly using self executing anonymous functions (or immediately executing if you're pedantic):
I think the simplest thing you can do is pass variables from one scope to a function outside that scope. If you pass by reference (like Objects), b has 'access' to it (see obj.someprop in the following):