Javascript模块模式范围与此

时间:2013-10-16 13:37:36

标签: javascript design-patterns

我正在使用模块模式进行开发,并且想知道为什么我无法使用它来访问模块范围。也许我对揭示模块模式的理解是错误的。

以下是我使用的代码:

var BLOG = window.BLOG || {};

BLOG.Module = (function(){

    var 
        _this = this,
        _hasLoaded = false;


    function init(){
        console.log(_this); // Logs the Window object

    }


    function _privateMethod(){
        $.ajax({
            url: 'lazyload/lazyload.html',
            success : function( data ){
                // _hasLoaded = true; // I want to access the variable in my module, How do I refer to it? 
            }

        });
    }


    return {
        init : init
    };

})();

1 个答案:

答案 0 :(得分:3)

this取决于函数的调用方式。如果直接调用它,而不是通过对象属性调用(因为你的外部作用域函数是),那么调用this将是松散模式下的全局对象(严格模式下为undefined)。在浏览器上,这是窗口对象。

通常不会使用this来尝试引用最外层范围函数内的内容(因此)。

如果有的话:

BLOG.Module.init();

...然后在init的调用中,this(不是_this)会引用Module,您可以参考您创建的对象的其他属性在最外层的范围界定功能结束时(目前没有任何其他功能,只有init)。


重新编辑:

var 
    _this = this,
    _hasLoaded = false;

// ...

function _privateMethod(){
    $.ajax({
        url: 'lazyload/lazyload.html',
        success : function( data ){
            // _hasLoaded = true; // I want to access the variable in my module, How do I refer to it? 
        }

    });
}

取消注释该行:

_hasLoaded = true;

这是因为调用_privateMethod后创建的_privateMethod和任何ajax成功处理程序都是闭包而不是最外层作用域函数中定义的变量。所以你只需要直接引用它们。

如果对“闭包”一词的使用不熟悉,请不要担心,closures are not complicated


旁注:这是一个奇怪的结构:

var BLOG = window.BLOG || {};

...因为它将需要它在全局范围内的代码与不要求它在全局范围内的代码混合在一起。它完全是功能性的,它有点奇怪。我可能会选择其中一种方式:

// Requires that it's at global scope (and yes, this does work)
var BLOG = BLOG || {};

// Creates a global whether it's at global scope or not
window.BLOG = window.BLOG || {};
相关问题