JavaScript 将作用域传递给另一个函数

发布于 2024-11-15 05:05:09 字数 301 浏览 6 评论 0原文

是否有可能以某种方式将一个函数的作用域传递给另一个函数?

例如,

function a(){
   var x = 5;
   var obj = {..};
   b(<my-scope>);
}

function b(){
   //access x or obj....
}

我宁愿直接访问变量,即不使用 this.athis.obj 之类的东西,而只使用 x或直接obj

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

梦途 2024-11-22 05:05:09

真正访问函数a的私有作用域的唯一方法是在a内部声明b,这样它就形成了一个允许隐式调用的闭包。访问a的变量。

这里有一些供您选择。

直接访问

  1. a内部声明b

    函数 a() {
       变量 x = 5,
          对象 = {};
       函数 b(){
          // 访问 x 或 obj...
       }
       b();
    }
    
    一个();
    
  2. 如果您不想将 b 放在 a 内,那么您可以将它们都放在更大的容器范围内:

    函数容器() {
       var x, obj;
       函数 a(){
          x = 5;
          对象 = {..};
          b();
       }
       函数 b(){
          // 访问 x 或 obj...
       }
    }
    
    容器.a();
    

这些是唯一的方法您将能够直接在 b 中使用 a 的变量,而无需一些额外的代码来移动事物。如果您满足于一点“帮助”和/或间接,这里还有一些想法。

间接访问

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

    函数 a() {
       变量 x = 5,
          对象 = {};
       b(x, 对象);
    }
    
    函数 b(x, obj){
       // 访问 x 或 obj...
       // 这里改变x不会改变a中的x,但你可以修改obj的属性
    }
    
    一个();
    

    作为此方法的变体,您可以通过将更新的值传递回 a 来获得写入权限,如下所示:

    // 在:
    var ret = b(x, obj);
    x = ret.x;
    obj = ret.obj;
    
    // 在 b 中:
    返回 {x: x, obj: obj};
    
  2. 您可以向 b 传递一个带有 getter 和 setter 的对象,这些 getter 和 setter 可以访问 a 的私有变量:

    函数 a(){
       变量 x = 5,
          对象 = {..},
          译者={
             getX : function() {返回 x;},
             setX : 函数(值) {x = 值;},
             getObj : function() {返回 obj;},
             setObj : 函数(值) {obj = 值;}
          };
       b(译者);
    }
    
    函数 b(t){
       var x = t.getX(),
          obj = t.getObj();
    
       // 使用 x 或 obj...
       t.setX(x);
       t.setObj(obj);
    
       // 或者你可以直接修改 obj 的属性:
       obj.key = 值;
    }
    
    一个();
    

    getter 和 setter 可以是公共的,分配给 athis 对象,但这样只有在 a 中显式给出时才能访问它们

  3. 您可以将变量放入一个对象中并传递该对象:

    函数 a(){
       变量 v = {
          x:5,
          对象:{}
       };
       b(v);
    }
    
    函数 b(v){
       // 访问 vx 或 v.obj...
       // 或为它们设置新的局部 x 和 obj 变量并使用它们。
    }
    
    一个();
    

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

    函数 a(){
       变量 x = 5,
          对象 = {};
       b({x : x, obj: obj});
    }
    
    函数 b(v){
       // 访问 vx 或 v.obj...
       // 或者为它们设置新的局部 x 和 obj 变量并使用它们。
    }
    
    一个();
    

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.

Here are some options for you.

Direct Access

  1. Declare b inside of a.

    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:

    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.

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:

    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.

  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();
    
dawn曙光 2024-11-22 05:05:09

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

}

虽然 b() 无法直接访问函数传递的变量,但如果函数传递返回,则可以访问传递引用的数据类型(例如对象) /em> 那个对象。

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

}

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

}
若有似无的小暗淡 2024-11-22 05:05:09

使用bind怎么样

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

what about using bind

function funcA(param) {     
    var bscoped = funcB.bind(this);     
    bscoped(param1,param2...)
}
无声情话 2024-11-22 05:05:09

不。

您正在访问本地范围对象。 [[上下文]]

无法公开访问它。

现在,由于它是 node.js,您应该能够编写一个 C++ 插件,让您可以访问 [[Context]] 对象。我强烈建议不要这样做,因为它给 JavaScript 语言带来了专有的扩展。

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.

烟花易冷人易散 2024-11-22 05:05:09

你不能“通过范围”……据我所知,情况并非如此。
您可以使用 applycall 传递函数引用的对象,并将当前对象 (this) 作为第一个参数发送仅调用函数:

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

函数访问特定范围的唯一方法是在该范围内声明。
有点棘手。
这会导致类似的结果:

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

但这有点违背了目的。

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:

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.

最终幸福 2024-11-22 05:05:09

正如其他人所说,你不能这样传递范围。但是,您可以使用自执行匿名函数正确地确定变量的范围(如果您比较迂腐,则可以立即执行):

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

a();

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

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

a();
在梵高的星空下 2024-11-22 05:05:09

我认为您可以做的最简单的事情就是将变量从一个作用域传递到该作用域之外的函数。如果您通过引用传递(如对象),则 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
}

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

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
}
回心转意 2024-11-22 05:05:09

你实际上只能通过 eval 来做到这一点。下面将给出函数 b 函数 a 的作用域

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

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
二手情话 2024-11-22 05:05:09
function a(){
   this.x = 5;
   this.obj = {..};
   var self = this;
   b(self);
}
function b(scope){
   //access x or obj....

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

}
内心荒芜 2024-11-22 05:05:09
function a(){
   var x = 5;
   var obj = {..};
   var b = function()
   {
        document.println(x);
   }
   b.call();
}
function a(){
   var x = 5;
   var obj = {..};
   var b = function()
   {
        document.println(x);
   }
   b.call();
}
夜空下最亮的亮点 2024-11-22 05:05:09

您是否尝试过这样的事情:

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

如果您可以将函数 B 作为方法函数 A,那么请执行以下操作:

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

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

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
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文