JavaScript将范围传递给另一个函数

时间:2021-12-23 19:42:16

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.

我宁愿直接访问变量,例如。而不是像这样。或者这个。obj,直接用x或obj。

11 个解决方案

#1


24  

The only way to truly get access to function a's private scope is to declare b inside of a so it forms a closure that allows implicit access to a's variables.

真正访问函数a的私有范围的唯一方法是在a中声明b,这样它就形成了一个闭包,允许对a的变量进行隐式访问。

Here are some options for you.

这里有一些你的选择。

Direct Access

直接访问

  1. Declare b inside of a.

    在a内部声明b。

    function a() {
       var x = 5,
          obj = {};
       function b(){
          // access x or obj...
       }
       b();
    }
    
    a();
    
  2. If you don't want b inside of a, then you could have them both inside a larger container scope:

    如果你不希望b在a里面,那么你可以把它们都放在一个更大的容器范围内:

    function container() {
       var x, obj;
       function a(){
          x = 5;
          obj = {..};
          b();
       }
       function b(){
          // access x or obj...
       }
    }
    
    container.a();
    

These are the only ways you're going to be able to use a's variables directly in b without some extra code to move things around. If you are content with a little bit of "help" and/or indirection, here are a few more ideas.

这是唯一一种不用额外代码就能直接在b中使用a的变量的方法。如果你满足于一点“帮助”和/或间接的帮助,这里有更多的想法。

Indirect Access

间接访问

  1. You can just pass the variables as parameters, but won't have write access except to properties of objects:

    您可以将变量作为参数传递,但是除了对象的属性之外,您没有写访问权限:

    function a() {
       var x = 5,
          obj = {};
       b(x, obj);
    }
    
    function b(x, obj){
       // access x or obj...
       // changing x here won't change x in a, but you can modify properties of obj
    }
    
    a();
    

    As a variation on this you could get write access by passing updated values back to a like so:

    作为一种变体,您可以通过将更新后的值传递回类似的:

    // in a:
    var ret = b(x, obj);
    x = ret.x;
    obj = ret.obj;
    
    // in b:
    return {x : x, obj : obj};
    
  2. You could pass b an object with getters and setters that can access a's private variables:

    你可以给b一个带有getter和setter的对象,该对象可以访问a的私有变量:

    function a(){
       var x = 5,
          obj = {..},
          translator = {
             getX : function() {return x;},
             setX : function(value) {x = value;},
             getObj : function() {return obj;},
             setObj : function(value) {obj = value;}
          };
       b(translator);
    }
    
    function b(t){
       var x = t.getX(),
          obj = t.getObj();
    
       // use x or obj...
       t.setX(x);
       t.setObj(obj);
    
       // or you can just directly modify obj's properties:
       obj.key = value;
    }
    
    a();
    

    The getters and setters could be public, assigned to the this object of a, but this way they are only accessible if explicitly given out from within a.

    getters和setters可以是公共的,分配给a的这个对象,但是只有在a中显式地给出时,它们才可以被访问。

  3. And you could put your variables in an object and pass the object around:

    你可以把你的变量放在一个对象中然后把对象传递出去:

    function a(){
       var v = {
          x : 5,
          obj : {}
       };
       b(v);
    }
    
    function b(v){
       // access v.x or v.obj...
       // or set new local x and obj variables to these and use them.
    }
    
    a();
    

    As a variation you can construct the object at call time instead:

    作为一种变体,您可以在调用时构造对象:

    function a(){
       var x = 5,
          obj = {};
       b({x : x, obj: obj});
    }
    
    function b(v){
       // access v.x or v.obj...
       // or set new local x and obj variables to these and use them.
    }
    
    a();
    

#2


8  

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().

作用域是由函数创建的,作用域与函数保持一致,因此最接近您要求的是将函数从a()传递到b(),该函数将继续访问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.

虽然b()不能直接访问函数传递的变量,但如果函数通过返回该对象,则可以访问引用的数据类型,比如对象。

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()

}

#3


6  

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.

现在因为它的节点。您应该能够编写一个c++插件,允许您访问[[[[Context]]]对象。我强烈建议不要这样做,因为它为JavaScript语言带来了专有的扩展。

#4


4  

what about using bind

如何使用绑定

function funcA(param) {     
    var bscoped = funcB.bind(this);     
    bscoped(param1,param2...)
}

#5


2  

As others have said, you cannot pass scope like that. You can however scope variables properly using self executing anonymous functions (or immediately executing if you're pedantic):

正如其他人所说,您不能通过这样的范围。但是,您可以使用自执行匿名函数(或者如果您是pedantic,则立即执行)来正确地确定变量的范围:

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

a();

#6


2  

I think the simplest thing you can do is pass variables from one scope to a function outside that scope. If you pass by reference (like Objects), b has 'access' to it (see obj.someprop in the following):

我认为你能做的最简单的事情就是将变量从一个范围传递到这个范围之外的函数。如果您通过引用(如对象)传递,那么b可以“访问”它(参见obj)。someprop在以下):

function a(){
   var x = 5;
   var obj = {someprop : 1};
   b(x, obj);
   alert(x); => 5
   alert(obj.someprop); //=> 'otherval'
}
function b(aa,obj){
   x += 1; //won't affect x in function a, because x is passed by value
   obj.someprop = 'otherval'; //change obj in function a, is passed by reference
}

#7


2  

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 or call and send the current object (this) as the first parameter instead of just calling the function:

你不能“通过范围”……我不知道。您可以通过使用apply或调用来传递函数所引用的对象,并将当前对象(this)作为第一个参数,而不是调用函数:

function b(){
    alert(this.x);
}
function a(){
    this.x = 2;
    b.call(this);
}

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 :

函数访问特定范围的唯一方法是在该范围中声明。这种棘手的。这将导致如下情况:

function a(){
    var x = 1;
    function b(){
        alert(x);
    }
}

But that would kind of defeat the purpose.

但这可能会破坏目标。

#8


-1  

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

}

#9


-1  

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

#10


-2  

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...

你可以在没有var关键字的情况下创建你的变量,它们将是全局的,但是没有办法通过我所知道的范围。

#11


-2  

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:

如果你能把函数B看成是方法a,那就这么做:

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

   this.b = function (){
      // "this" keyword is still === function a
   }
}

#1


24  

The only way to truly get access to function a's private scope is to declare b inside of a so it forms a closure that allows implicit access to a's variables.

真正访问函数a的私有范围的唯一方法是在a中声明b,这样它就形成了一个闭包,允许对a的变量进行隐式访问。

Here are some options for you.

这里有一些你的选择。

Direct Access

直接访问

  1. Declare b inside of a.

    在a内部声明b。

    function a() {
       var x = 5,
          obj = {};
       function b(){
          // access x or obj...
       }
       b();
    }
    
    a();
    
  2. If you don't want b inside of a, then you could have them both inside a larger container scope:

    如果你不希望b在a里面,那么你可以把它们都放在一个更大的容器范围内:

    function container() {
       var x, obj;
       function a(){
          x = 5;
          obj = {..};
          b();
       }
       function b(){
          // access x or obj...
       }
    }
    
    container.a();
    

These are the only ways you're going to be able to use a's variables directly in b without some extra code to move things around. If you are content with a little bit of "help" and/or indirection, here are a few more ideas.

这是唯一一种不用额外代码就能直接在b中使用a的变量的方法。如果你满足于一点“帮助”和/或间接的帮助,这里有更多的想法。

Indirect Access

间接访问

  1. You can just pass the variables as parameters, but won't have write access except to properties of objects:

    您可以将变量作为参数传递,但是除了对象的属性之外,您没有写访问权限:

    function a() {
       var x = 5,
          obj = {};
       b(x, obj);
    }
    
    function b(x, obj){
       // access x or obj...
       // changing x here won't change x in a, but you can modify properties of obj
    }
    
    a();
    

    As a variation on this you could get write access by passing updated values back to a like so:

    作为一种变体,您可以通过将更新后的值传递回类似的:

    // in a:
    var ret = b(x, obj);
    x = ret.x;
    obj = ret.obj;
    
    // in b:
    return {x : x, obj : obj};
    
  2. You could pass b an object with getters and setters that can access a's private variables:

    你可以给b一个带有getter和setter的对象,该对象可以访问a的私有变量:

    function a(){
       var x = 5,
          obj = {..},
          translator = {
             getX : function() {return x;},
             setX : function(value) {x = value;},
             getObj : function() {return obj;},
             setObj : function(value) {obj = value;}
          };
       b(translator);
    }
    
    function b(t){
       var x = t.getX(),
          obj = t.getObj();
    
       // use x or obj...
       t.setX(x);
       t.setObj(obj);
    
       // or you can just directly modify obj's properties:
       obj.key = value;
    }
    
    a();
    

    The getters and setters could be public, assigned to the this object of a, but this way they are only accessible if explicitly given out from within a.

    getters和setters可以是公共的,分配给a的这个对象,但是只有在a中显式地给出时,它们才可以被访问。

  3. And you could put your variables in an object and pass the object around:

    你可以把你的变量放在一个对象中然后把对象传递出去:

    function a(){
       var v = {
          x : 5,
          obj : {}
       };
       b(v);
    }
    
    function b(v){
       // access v.x or v.obj...
       // or set new local x and obj variables to these and use them.
    }
    
    a();
    

    As a variation you can construct the object at call time instead:

    作为一种变体,您可以在调用时构造对象:

    function a(){
       var x = 5,
          obj = {};
       b({x : x, obj: obj});
    }
    
    function b(v){
       // access v.x or v.obj...
       // or set new local x and obj variables to these and use them.
    }
    
    a();
    

#2


8  

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().

作用域是由函数创建的,作用域与函数保持一致,因此最接近您要求的是将函数从a()传递到b(),该函数将继续访问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.

虽然b()不能直接访问函数传递的变量,但如果函数通过返回该对象,则可以访问引用的数据类型,比如对象。

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()

}

#3


6  

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.

现在因为它的节点。您应该能够编写一个c++插件,允许您访问[[[[Context]]]对象。我强烈建议不要这样做,因为它为JavaScript语言带来了专有的扩展。

#4


4  

what about using bind

如何使用绑定

function funcA(param) {     
    var bscoped = funcB.bind(this);     
    bscoped(param1,param2...)
}

#5


2  

As others have said, you cannot pass scope like that. You can however scope variables properly using self executing anonymous functions (or immediately executing if you're pedantic):

正如其他人所说,您不能通过这样的范围。但是,您可以使用自执行匿名函数(或者如果您是pedantic,则立即执行)来正确地确定变量的范围:

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

a();

#6


2  

I think the simplest thing you can do is pass variables from one scope to a function outside that scope. If you pass by reference (like Objects), b has 'access' to it (see obj.someprop in the following):

我认为你能做的最简单的事情就是将变量从一个范围传递到这个范围之外的函数。如果您通过引用(如对象)传递,那么b可以“访问”它(参见obj)。someprop在以下):

function a(){
   var x = 5;
   var obj = {someprop : 1};
   b(x, obj);
   alert(x); => 5
   alert(obj.someprop); //=> 'otherval'
}
function b(aa,obj){
   x += 1; //won't affect x in function a, because x is passed by value
   obj.someprop = 'otherval'; //change obj in function a, is passed by reference
}

#7


2  

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 or call and send the current object (this) as the first parameter instead of just calling the function:

你不能“通过范围”……我不知道。您可以通过使用apply或调用来传递函数所引用的对象,并将当前对象(this)作为第一个参数,而不是调用函数:

function b(){
    alert(this.x);
}
function a(){
    this.x = 2;
    b.call(this);
}

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 :

函数访问特定范围的唯一方法是在该范围中声明。这种棘手的。这将导致如下情况:

function a(){
    var x = 1;
    function b(){
        alert(x);
    }
}

But that would kind of defeat the purpose.

但这可能会破坏目标。

#8


-1  

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

}

#9


-1  

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

#10


-2  

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...

你可以在没有var关键字的情况下创建你的变量,它们将是全局的,但是没有办法通过我所知道的范围。

#11


-2  

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:

如果你能把函数B看成是方法a,那就这么做:

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

   this.b = function (){
      // "this" keyword is still === function a
   }
}