Javascript为什么要在IIFE中包装变量或构造函数? [英] Javascript why wrap a variable or constructor in an IIFE?

查看:110
本文介绍了Javascript为什么要在IIFE中包装变量或构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天看到这样的事情

var Visualizer = (function() {
  function Visualizer() {
    ...
  }
  Vizualizer.prototype.function1 = function () { ... }
  ...
  return Visualizer;
})();

var viz = new Visualizer();

我不明白这一点与仅仅摆脱了生命包装。

I don't understand the point of this versus just getting rid of the iife wrapper.

推荐答案

您在此处显示的具体构造没有意义。在这种类型的构造中使用IIFE的原因是,当您拥有需要声明的静态数据,希望对象可用,但不希望它可公开访问或干扰全局命名空间或是实例时数据。

There's no point for the specific construct that you show here. The reason to use an IIFE in this type of construct is when you have static data that you need to declare, want to be available to your object, but don't want it to be publicly accessible or interfere with the global namespace or be instance data.

由于您展示的代码没有显示任何这些代码,因此您并未真正提供任何好处,如您所示。但是,如果在对象外部声明了一些其他变量,但在IIFE内部,那么IIFE将保护并封闭它们并将它们与外界隔离。

Since the code you show doesn't show any of those, it isn't really offering any benefit as you've shown. But, if there were some other variables declared outside the object, but inside the IIFE, then the IIFE would protect and enclose them and isolate them from the outside world.

For例如,如果你有这个:

For example, if you had this:

Visualizer = (function() {
  var counter = 0;
  function Visualizer() {
    counter++;
    ...
  }
  Visualizer.prototype.getCount = function () { return counter; }
  ...
  return Visualizer;
})();

var viz = new Visualizer();

然后,IIFE将附上一个变量柜台可用于Visualizer所有实例的所有方法,但与外界隔离,IIFE将提供一些潜在的好处。

Then, the IIFE would be enclosing a variable counter that would be available to all methods of all instances of Visualizer, but isolated from the outside world and the IIFE would be offering some potential benefit.

这篇关于Javascript为什么要在IIFE中包装变量或构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆