参考IIFE内部的功能

dav*_*qet 2 javascript logic closures function iife

我有以下逻辑:

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

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

first_function.third_function(data1, data2);
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Jon*_*ams 5

如果要从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);
Run Code Online (Sandbox Code Playgroud)

有趣的是,我们也可以利用这个来创建"私有"方法和变量.

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);
Run Code Online (Sandbox Code Playgroud)

如果您想了解有关其工作原理的更多信息,建议您阅读JavaScript范围和闭包.