访问由闭包捕获的变量 [英] Accessing variables trapped by closure

查看:109
本文介绍了访问由闭包捕获的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法从函数外部访问函数中闭包所捕获的变量;例如如果我有:

I was wondering if there is any way to access variables trapped by closure in a function from outside the function; e.g. if I have:


A = function(b) {
    var c = function() {//some code using b};
    foo: function() {
        //do things with c;
    }
}

有没有办法访问 c A 的实例中。类似于:

is there any way to get access to c in an instance of A. Something like:


var a_inst = new A(123);
var my_c = somejavascriptmagic(a_inst);


推荐答案

闭包内的变量不是直接 无论如何都可以从外面访问。但是,具有变量范围的闭包内的闭包可以访问它们,如果你从外部访问这些闭包,它几乎一样好。

Variables within a closure aren't directly accessible from the outside by any means. However, closures within that closure that have the variable in scope can access them, and if you make those closures accessible from the outside, it's almost as good.

这是一个例子:

var A = function(b) {
    var c = b + 100;
    this.access_c = function(value) {
        // Function sets c if value is provided, but only returns c if no value
        // is provided
        if(arguments.length > 0)
            c = value;
        return c;
    };
    this.twain = function() {
        return 2 * c;
    };
};
var a_inst = new A(123);
var my_c = a_inst.access_c();
// my_c now contains 223
var my_2c = a_inst.twain();
// my_2c contains 446
a_inst.access_c(5);
// c in closure is now equal to 5
var newer_2c = a_inst.twain();
// newer_2c contains 10

希望这对你有用......

Hopefully that's slightly useful to you...

这篇关于访问由闭包捕获的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆