参考IIFE内部的功能

时间:2015-10-20 21:31:44

标签: javascript function logic closures 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);

我哪里错了?

2 个答案:

答案 0 :(得分: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);

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

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范围和闭包。

答案 1 :(得分:2)

它没有返回它,所以功能只是蒸发。你可以这样做:

person* persons[];

function () {
    initialize global array here
}

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

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