我想可以肯定,http://eloquentjavascript.net/10_modules.html,例如:EloquentJavaScript - 通過此關鍵字引用不起作用?
(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")));
// → weekDay not defined
,當我在提到網站上運行的工作,但是當我嘗試做同樣的VS代碼(+ Node.js的調試),它說weekDay
未定義。我已經發現原因是這個關鍵字不是引用保存整個代碼的對象,而是指保存調用該函數的對象的對象,所以我試過這個:
它的工作原理,任何人都可以解釋爲什麼? IMO傳遞的參數不被視爲函數變量,而是屬於調用該函數的對象的變量(但爲什麼從書上的代碼在網站上工作呢?)。
(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); }; })(weekDay = {}); console.log(weekDay.name(weekDay.number("Saturday"))); // → Saturday