Javascript why include a variable or constructor in IIFE?

I saw something like this today

var Visualizer = (function() { function Visualizer() { //... } Visualizer.prototype.function1 = function () { /* ... */ } //... return Visualizer; })(); var viz = new Visualizer(); 

I don't understand the meaning of this compared to just getting rid of the iife wrapper.

+6
source share
3 answers

It makes no sense for the specific design that you are showing here. The reason for using IIFE in this type of construct is when you have static data that needs to be declared, want to be available to your object, but don't want it to be publicly available or interfere with the global namespace or be an instance of data.

Since the code that you show does not show any of them, it does not offer any advantages, as you showed. But if there were any other variables declared outside the object, but inside IIFE, then IIFE would protect and close them and isolate them from the outside world.

For example, if you have this:

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

Then IIFE will include the counter variable, which will be accessible to all methods of all Visualizer instances, but isolated from the outside world, and IIFE will offer some potential benefits.

+21
source

In case there will be many visualizers, function1 will be the same instance in all of them. As discussed here, the IIFE leakage method .

0
source

Sorry, I phrased it vaguely, but I think that the JS with the spoken words should be the bracket in order to know which operation takes precedence and what belongs to what is equivalent simply by saying β€œI know what's what” and stating that python simply said that if he did not have these brackets, he would properly resort to a method like python where there is no need for brackets; where padding is important. Perhaps I missed the whole question, but I think I got it right.

-3
source

All Articles