在 IIFE 中引用一个函数

Reference a function inside an IIFE

我有以下逻辑:

var first_function = (function(d3, second_function) {
  function third_function(param1, param2) {
    /* do stuff here */
  }
})(d3, second_function);

在 IIFE 结构之外,要访问第三个函数,我通常可以这样做:

first_function.third_function(data1, data2);

我哪里错了?

它没有返回它,所以函数只是蒸发了。你可以这样做:

var first_function = (function(d3, second_function) {
  function third_function(param1, param2) {
    /* do stuff here */
  }
  return third_function;
})(d3, second_function);

然后,您可以这样访问它:

first_function( paramForThirdFunc1,paramForThirdFunc2);

如果您想从 IIFE 访问 属性,您需要通过返回对象

使 属性 可用
var first_function = (function(d3, second_function) {

  // this function is unavailable to the outer scope
  function third_function(param1, param2) {
  /* do stuff here */
  }

  // this object allows us to access part of the inner scope
  // by passing us a reference
  return {
    third_function: third_function
  }
}})(d3, second_function);

有趣的是,我们还可以利用它来创建 'private' 方法和变量。

var first_function = (function(d3, second_function) {

  // this function is unavailable to the outer scope
  function third_function(param1, param2) {
  /* do stuff here */
  }

  var myPrivate = 0; // outer scope cannot access

  // this object allows us to access part of the inner scope
  // by passing us a reference
  return {
    third_function: third_function,
    getter: function() {
      return myPrivate;   // now it can, through the getter 
    }
  }
}})(d3, second_function);

如果您想详细了解其工作原理,我建议您阅读 JavaScript 作用域和闭包。