[英]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.