简体   繁体   中英

Javascript module pattern scope with this

I was developing using module pattern, and was wondering why I can't acces to the module scope using this. Maybe I'm wrong with the understanding of the revealing module pattern.

Here is the code I use :

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 is determined by how a function is called. If it's called directly, not through an object property (as your outer scoping function is), within that call this will be the global object in loose mode ( undefined in strict mode). On browsers, that's the window object.

You wouldn't normally use this to try to refer to things within that outermost scoping function (for this reason).

If something did this:

BLOG.Module.init();

...then within the call to init , this (not _this ) would refer to Module and you could refer to other properties on the object you create at the end of your outermost scoping function (there aren't any others currently, just init ).


Re your edit:

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

    });
}

Just uncomment that line:

_hasLoaded = true;

This is because both _privateMethod and any ajax success handlers created as a result of calling _privateMethod are closures over the variables defined within your outermost scoping function. So you just refer to them directly.

If this use of the word "closure" is unfamiliar, don't worry, closures are not complicated .


Side note: This is an odd construct:

var BLOG = window.BLOG || {};

...as it mixes code requiring that it be at global scope with code that doesn't require that it be at global scope. It's entirely functional, it's just a bit odd. I'd probably go one way or the other:

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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