javascript - 括号中带有 "this.variable"的立即调用函数表达式

标签 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

最佳答案

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

(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

关于javascript - 括号中带有 "this.variable"的立即调用函数表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749361/

相关文章:

javascript - jquery fadeIn 函数作为回调函数,带有 $ ("this") 参数

node.js - 如何在 Angular 2 应用程序中包含时刻时区

mysql - Express js中使用mysql进行文件上传

node.js - 如何将 Express 服务器和 html 脚本捆绑到同一个 Node Webkit 应用程序中?

node.js - TypeScript:使用ZeroMQ ROUTER/DEALER时占用大量内存

node.js - 如何在 webpack 中隐藏代码而不是在 node.js 中

javascript - jQuery 的动态宽度 = 高度

javascript - 获取 PHP URL 的 JS 值

javascript - 如何调试失败的 Angular 选择(或任何其他类型)绑定(bind)?

javascript - 简化 BigCommerce 结账页面