【问题标题】:Access outer members in Javascript module访问 Javascript 模块中的外部成员
【发布时间】:2013-05-21 14:48:57
【问题描述】:

我有一个模块

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

从上面的代码可以看出,我想通过使用一些 magicaOccursHere 来访问this 范围之外的属性...

我之前通过使模块返回一个函数而不是 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 的混乱模式和代码是否过于苛刻?

【问题讨论】:

    标签: javascript module scope closures


    【解决方案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"
               });
        }
    }
    

    【讨论】:

    • 仔细想想,这一切都是那么简单明了。非常感谢。
    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 2016-12-08
    • 2022-01-14
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多