JavaScript pass scope to another function

Viewed 24381

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.

11 Answers

You can really only do this with eval. The following will give function b function a's scope

  function a(){
     var x = 5;
     var obj = {x};
     eval('('+b.toString()+'())');
  }
  
  function b(){
     //access x or obj....
     console.log(x);
  }
  
  a();  //5
Related