An analysis of the pros and cons and differences between the two ways JavaScript creates closures

  • 2020-06-19 09:41:08
  • OfStack

There are two common ways in which JavaScript creates closures.

Constructor method:


new function() { 
var  variable ... 
} 

Inline execution mode:


(function() { 
var  variable ... 
})(); 

What are the differences between them under JavaScript's internal operating mechanism? What is the best way to create it? What advantage does it have over closures created in other ways?

Here's how I understand it:

The difference between:

1: Submethods can share variables
Second: Internal sub-methods share variables

Comparison:

I think inline is better;

Advantage:

1 as inline is created on demand for memory, because only the local variables of execution in memory, related and dependent code can be organized, in order to minimize the risk of accidental interaction, structure the method performs all variables are stored in the memory, it will influence the performance of the page, suggest to delete variables before exit

Of course, this is just my personal understanding, in fact, the use of closures in general requires a particular memory leak mainly in the IE kernel browser, and it is best to use variables as soon as possible.

This is the end of this article, I hope you enjoy it


Related articles: