JavaScript pass scope to another function

后端 未结 10 577
被撕碎了的回忆
被撕碎了的回忆 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:29

    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() to b(), and that function will continue to have access to the scoped variables from a().

    function a(){
       var x = 5;
       var obj = {..};
       b(function() { /* this can access var x and var obj */ });
    }
    function b( fn ){
    
        fn(); // the function passed still has access to the variables from a()
    
    }
    

    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.

    function a(){
       var x = 5;
       var obj = {..};
       b(function() { x++; return obj; });
    }
    function b( fn ){
    
        var obj = fn();
        obj.some_prop = 'some value'; // This new property will be updated in the
                                      //    same obj referenced in a()
    
    }
    

提交回复
热议问题