This question has already been answered:

There is such code:

var f = function() { this.x = 5; (function() { this.x = 3; })(); console.log(this.x); } 

Why the function inside the function is written like this:

 (function() { this.x = 3; })(); 

And why can not write like this:

 function() { this.x = 3; } 

?

Reported as a duplicate by Grundy , user194374, aleksandr barakin , Bald , fori1ton July 8, '16 at 15:41 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • oh how bad everything is, and where did you find such a code? - Grundy
  • Grundy, in Habré found such code. Here is the source: habrahabr.ru/post/149516 - Ilnyr
  • Alexey Ten, my question is not very similar to what they took off the source. Those. firstly not a duplicate, and secondly the answers are not satisfied. - Ilnyr
  • @Ilnyr, no, in this edition your question is an absolute duplicate of the one provided by the link. If the question implies something else, you should add it - Grundy
  • one
    This is yes, but I also have the keyword this. Is it not different things? And in this source, I don’t see any mention of this in the "wrapper" - Ilnyr

1 answer 1

This is called a "wrapper", you declare a function and immediately call it. In the second case, I had to write this:

 var f1=function(_this) { _this.x = 3; } f1(this); 

The point is that in the "wrapper" this accepts not the value of the function itself, but the value of the external function.

  • Why would you have to write in the second case? Where did the parameter come from? - Grundy
  • which means in the "wrapper" this takes not the value of the function itself, but the value of the external function. ? - Grundy
  • Yes, details about the last paragraph are also interesting - Ilnyr
  • this means that the wrapper uses this parent scope. - iKest
  • @iKest, the code given in the answer is not similar to what is given in the question - Grundy