2015-08-23 47 views
-2

我發現這個代碼,我無法從this passage of Eloquent JavaScript明白:如何從Eloquent JavaScript中「導出」?

(function(exports) { 
    var names = [" Sunday ", " Monday ", " Tuesday ", " Wednesday ", 
       " Thursday ", " Friday ", " Saturday "]; 
    exports.name = function(number) { 
     return names[number]; 
    }; 
    exports.number = function (name) { 
     return names.indexOf (name); 
    }; 
})(this.weekDay = {}); 

console.log(weekDay.name(weekDay.number("Saturday"))); 

特別是,我無法理解this.weekDay:什麼是this這裏? 以及我們如何訪問weekDay.name - 它在函數的範圍內,所以我們如何從函數中訪問它?

回答

1

在全球範圍內,this指全局對象(它是在網絡瀏覽器windowglobal在Node.js的)。因此,在這種情況下,分配this.weekDay = {}等於window.weekDay = {}weekDay = {},所有這些都創建一個名爲weekDay的全局變量。關於使用this而不是window的好處是您可以對瀏覽器和節點使用相同的表示法。在模塊定義下面對weekDay的引用只是指全局變量weekDay;它們也可以寫成this.weekDaywindow.weekDay

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

1

weekDay不是在所示的功能範圍內訪問; exports是。

分配給weekDay被提供作爲參數傳遞給IIFE(立即調用的函數表達式)新對象(即this.weekDay = {});並因此修改函數內部的對象(通過exports)影響其他地方的同一對象。

..由於原始分配,此對象在調用作用域中被稱爲weekDay(全局變量)。

(function (exports) { 
    // in function 
})(this.weekDay = {}); // <-- not in function, 'this.' is superfluous