【问题标题】:How do I access parent functions closure in javascript?如何在 javascript 中访问父函数闭包?
【发布时间】:2012-04-29 09:23:00
【问题描述】:

在以下情况下如何访问父函数“var”变量(我只能编辑重置函数的定义):

_.bind(function(){
    var foo = 5;

    var reset = function(){
        foo = 6;  //this changes foo,
        bar = 7;  //**I want this to add another "var", so I don't pollute global scope
    }
    reset();
    console.log(foo); //6
    console.log(bar); //7
}, window);

【问题讨论】:

    标签: javascript scope closures


    【解决方案1】:

    对不起,你不能。

    访问命名空间的唯一方法是with 语句。

    例如,如果您能够重写整个内容,则可以这样完成:

    _.bind(function(){
        var parentNamespace = {
            foo: 5,
        };
    
        with (parentNamespace) {
            var reset = function(){
                foo = 6;  //this changes foo,
                parentNamespace.bar = 7;  //**I want this to add another "var", so I don't pollute global scope
            }
            reset();
            console.log(foo); //6
            console.log(bar); //7
        }
    }, window);
    

    但这很可能几乎肯定是个坏主意。

    【讨论】:

    • 并且只添加一个 obj 到 scrope
    • with 在 JavaScript 中是一个可怕的声明,这是有充分理由的。
    【解决方案2】:

    这对你有用吗?

    _.bind(function(){
        var foo = 5, bar;
    
        var reset = function(){
            foo = 6;  //this changes foo,
            bar = 7;  //**I want this to add another "var", so I don't pollute global scope
        }
        reset();
        console.log(foo); //6
        console.log(bar); //7
    }, window);
    

    【讨论】:

    • 这是一个很好的方法。如果要使封闭范围可访问名副其实,则必须在封闭范围中声明它
    • 是的,这就是我现在的样子,我只是对所有名称的重复感到沮丧。
    【解决方案3】:

    我不确定我是否理解你的问题,所以我的答案可能不是你想要的。

    var reset = function(){
        foo = 6;  
        reset.bar = 7;   
    }
    reset.bar = 13;
    reset();  // reset.bar is back to 7.
    

    【讨论】:

      【解决方案4】:

      ECMA-262 明确禁止访问函数的变量对象(函数实际上不必有一个,它们只需要表现得好像有),所以你不能访问它。

      您只能通过在适当的范围内声明变量或将它们包含在FunctionDeclarationFunctionExpression的形参列表中来添加属性,没有其他方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 2013-04-24
        • 1970-01-01
        相关资源
        最近更新 更多