I started to figure it out with javascript template engines, and in the examples I see the following entry everywhere:

(function(){ this.var1 = function(){ }, this.var2 = function(){ }; return function(){ }; })(); 

Could someone tell me about it. What is it, what is needed, how is it used, what is the meaning of such a record?

  • And what exactly is not clear? In the first brackets - the definition of the function, the final pair of brackets - its call. - VladD

2 answers 2

This syntax means that the anonymous function will be called immediately.

  • This I basically knew before, and what will happen to this.var1? - Stanislav Dalinin
  • @ Stanislav Dalinin, if I'm not mistaken, this in the context of this function refers to the window object - mountpoint
  • @Stanislav Dalinin These functions (methods) will look outside. Equivalent window.var1 = function () {} - romeo
  • That is, in the future, to call var1, it suffices to write var1 (); ? And why do we need a second pair of parentheses ()? - Stanislav Dalinin
  • @Stanislav Dalinin The basic meaning of this construction is to isolate the scope, a kind of module. In your example, this is not done, for both methods stick out. - romeo

As far as I understand, this refers to the object whose method the function is. If it is not a user object method, then this refers to the window.