立即调用函数表达式,括号中带有“this.variable”

时间:2017-06-25 18:32:31

标签: javascript node.js

为什么声明一个立即调用的函数定义,然后在最后的另一个括号中使用“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

1 个答案:

答案 0 :(得分:3)

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



(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