JavaScript pass scope to another function

后端 未结 10 583
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 16:48

Is it possible to somehow pass the scope of a function to another?

For example,

function a(){
   var x = 5;
   var obj = {..};
   b()         


        
10条回答
  •  生来不讨喜
    2020-12-23 17:27

    Have you tried something like this:

    function a(){
       var x = 5;
       var obj = {..};
       b(this);
    }
    function b(fnA){
       //access x or obj....
       fnA.obj = 6;
    }
    

    If you can stand function B as a method function A then do this:

    function a(){
       var x = 5;
       var obj = {..};
       b(this);
    
       this.b = function (){
          // "this" keyword is still === function a
       }
    }
    

提交回复
热议问题