简体   繁体   English

参考IIFE内部的功能

[英]Reference a function inside an IIFE

I have the following logic: 我有以下逻辑:

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

Outside of an IIFE structure, to access the third function, I could normally do something like: 在IIFE结构之外,要访问第三个函数,我通常可以这样做:

first_function.third_function(data1, data2);

Where am I going wrong? 我哪里错了?

If you want to access a property from an IIFE, you need to make that property available by returning an object 如果要从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);

Interestingly enough, we can also take advantage of this to create 'private' methods and variables. 有趣的是,我们也可以利用这个来创建“私有”方法和变量。

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

If you want to learn more about how this works, I suggest you read up on JavaScript scopes and closures. 如果您想了解有关其工作原理的更多信息,建议您阅读JavaScript范围和闭包。

Its not returning it, so the function is just evaporating. 它没有返回它,所以功能只是蒸发。 You can do something like this: 你可以这样做:

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

Then, you can access it like this: 然后,您可以像这样访问它:

first_function( paramForThirdFunc1,paramForThirdFunc2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM