【发布时间】: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_function是undefined? -
你的 IIFE 返回什么?您需要返回一个具有 third_function 作为属性的对象,否则您将无法访问它。
-
另外,你不能在 IIFE 之外访问
third_function,这就是闭包的作用,内部函数在外部范围内不可用,除非你返回一些东西使它可用。真正的问题变成了;你为什么要使用 IIFE? -
欣赏见解,@adeneo。我主要是使用 IIFE 来更好地了解它们,同时也不会对全球造成污染。
标签: javascript function logic closures iife