Accessing variables trapped by closure

前端 未结 6 597
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 06:38

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) {
    va         


        
6条回答
  •  爱一瞬间的悲伤
    2020-11-29 06:47

    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.

    Here's an example:

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

提交回复
热议问题