0

我有一个模块

something = {
    value : "",
    anotherVal : "",
    method : function(){
           this.anotherVal = "I think it is accessable here";
           GLOBAL.action(
           func : function(){
               // In here I want to access the above value.
               // Which is a property of the outer something module.
               <![magicOccursHere]!>.value = "magically access outer scope"
           });
    }
}

正如您从上面的代码中看到的那样,我想this通过使用一些magicaOccursHere 来访问范围之外的属性......

我之前通过使模块返回一个函数而不是 json 对象然后命名每个级别来做到这一点。但我不喜欢这种语法。

SOMETHING = new Something();
something = function Something() {
    var bigDaddy = this;
    this.value = "";
    this.anotherVal = "";
    this.method = function(){
           bigdaddy.anotherVal = "Set one of big daddies vars";
           GLOBAL.action(
           func : function(){
               // In here I want to access the above value.
               // Which is a property of the outer something module.
               bigdaddy.value = "can still set one of big daddies vars"
           });
    }
}

我可能完全错过了这里的重点,如果您想指出我的意思,那么我很乐意阅读。

我对选项 2 的混乱模式和代码是否过于苛刻?

4

1 回答 1

1

如果您在method函数内部创建一个局部变量,它将在内部范围内func

var something = {
    value : "",
    anotherVal : "",
    method : function(){
           var obj = this;
           this.anotherVal = "I think it is accessable here";
           GLOBAL.action(
           func : function(){
               // In here I want to access the above value.
               // Which is a property of the outer something module.
               obj.anotherVal = "magically access outer scope"
           });
    }
}

或者您可以使用完全限定路径:

var something = {
    value : "",
    anotherVal : "",
    method : function(){
           this.anotherVal = "I think it is accessable here";
           GLOBAL.action(
           func : function(){
               // In here I want to access the above value.
               // Which is a property of the outer something module.
               something.anotherVal = "magically access outer scope"
           });
    }
}
于 2013-05-21T14:51:49.617 回答