【问题标题】:Reference a function inside an IIFE引用 IIFE 中的函数
【发布时间】:2016-01-19 17:36:00
【问题描述】:

我的逻辑如下:

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);

我哪里出错了?

【问题讨论】:

  • 注意IIFE不返回任何东西,它立即执行,所以基本上first_functionundefined
  • 你的 IIFE 返回什么?您需要返回一个具有 third_function 作为属性的对象,否则您将无法访问它。
  • 另外,你不能在 IIFE 之外访问third_function,这就是闭包的作用,内部函数在外部范围内不可用,除非你返回一些东西使它可用。真正的问题变成了;你为什么要使用 IIFE?
  • 欣赏见解,@adeneo。我主要是使用 IIFE 来更好地了解它们,同时也不会对全球造成污染。

标签: javascript function logic closures iife


【解决方案1】:

如果你想从 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 作用域和闭包。

【讨论】:

  • 是的,这正是他想要的。
  • 我希望我能给你们两个答案。 Harshal 只是更快,尽管这是一个更完整的答案,我感谢你。
【解决方案2】:

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

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);

【讨论】:

  • 试试这个。将尽快报告。
  • @daveycroqet 我弄错了,再检查一遍:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 2020-08-13
  • 1970-01-01
  • 2018-05-30
  • 2016-12-24
  • 1970-01-01
相关资源
最近更新 更多