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.
You can't "pass the scope"... not that I know of.
You can pass the object that the function is referring to by using
apply
orcall
and send the current object (this
) as the first parameter instead of just calling the function:The only way for a function to access a certain scope is to be declared in that scope.
Kind'a tricky.
That would lead to something like :
But that would kind of defeat the purpose.
Scope is created by functions, and a scope stays with a function, so the closest thing to what you're asking will be to pass a function out of
a()
tob()
, and that function will continue to have access to the scoped variables froma()
.While
b()
doesn't have direct access to the variables that the function passed does, data types where a reference is passed, like an Object, can be accessed if the function passed returns that object.You can create your variables without the
var
keyword and they will be global, but no way to pass the scope that I'm aware of...what about using
bind