JavaScript pass scope to another function

后端 未结 10 579
被撕碎了的回忆
被撕碎了的回忆 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
       }
    }
    
    0 讨论(0)
  • 2020-12-23 17:28
    function a(){
       this.x = 5;
       this.obj = {..};
       var self = this;
       b(self);
    }
    function b(scope){
       //access x or obj....
    
    }
    
    0 讨论(0)
  • 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()
    
    }
    
    0 讨论(0)
  • 2020-12-23 17:36

    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.

    0 讨论(0)
提交回复
热议问题