繁体   English   中英

与此相关的Javascript模块模式范围

[英]Javascript module pattern scope with this

我正在使用模块模式进行开发,并且想知道为什么我不能使用此模块范围。 也许我对显示模块模式的理解是错误的。

这是我使用的代码:

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

})();

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成功处理程序都是对最外层作用域函数中定义的变量的闭包 因此,您只需要直接引用它们即可。

如果对“ closure”一词的这种用法不熟悉,请不用担心, closure并不复杂


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

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 || {};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM