2

在以下情况下,我将如何访问父函数“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);
4

4 回答 4

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

但这是最有可能的几乎可以肯定是个坏主意。

于 2012-04-18T01:03:11.257 回答
1

这对你有用吗?

_.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);
于 2012-04-18T01:03:51.967 回答
0

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

var reset = function(){
    foo = 6;  
    reset.bar = 7;   
}
reset.bar = 13;
reset();  // reset.bar is back to 7.
于 2012-04-18T01:59:00.353 回答
0

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

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

于 2012-04-18T03:14:25.570 回答