带有“this.variable”的即时调用函数expression式

为什么要声明一个立即调用的函数定义,然后在另一个括号中使用“this.variable”,或许作为一个参数? 代码给出的结果是“星期六”,但你能解释这个代码是如何工作的?

(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"))); // → Saturday 

谢谢!

也许这会让你更容易理解。

 (function() { // an object for my this, rather than the global this function iife(exports) { // only accessible within the iife context var names = [ 'Sunday', // index number 0 'Monday', // 1 'Tuesday', // 2 'Wednesday', // 3 'Thursday', // 4 'Friday', // 5 'Saturday' // 6 ]; // assign property name to the exports object with function as value exports.name = function(number) { return names[number]; }; // assign property number to the exports object with function as value exports.number = function(name) { return names.indexOf(name); }; } // assign property weekDay to the this object with object as value this.weekDay = {}; // call iife with the first argument as our object's reference iife(this.weekDay); // we can see weekDay on our this object with the assigned properties console.log(this); // call the number function on the weekDay namespace // If we had access to names: names.indexOf('Saturday') -> 6 var dayNumber = this.weekDay.number('Saturday'); console.log(dayNumber); // call the name function on the weekDay namespace // If we had access to names: names[6] -> 'Saturday' var dayName = this.weekDay.name(dayNumber); console.log(dayName); }).call({}); // make my this object