Does it make sense for this piece of code?

Tonight is late tonight, so I can’t function normally, but I found this piece of code, and I can’t understand why it is used this way ( NOTE : I understand what it does, what I do not understand is the value worth after him).

(function() { var narcissus = { options: { version: 185, }, hostGlobal: this }; Narcissus = narcissus; })(); 

Autonomous anonymous functions are used to avoid contamination of the global namespace, but this code should not introduce other variables than Narcissus , so it could easily be rewritten as Narcissus = {...}; . Some possible reasons I can think of are future checks for a lack of code or implementation. Something I do not see?

+6
source share
2 answers

In terms of maintainability, it allows the author to later add code to the Closure area, which has not seeped between the creation of narcissus and the appointment of narcissus . Although in this case there is no code, so I see no advantages other than the above things mentioned.

+1
source

Part of your flaw is that javascript is a case sensitive language, so

 Narcissus != narcissus; 

It adds Narcissus to the global scope, omitting the var keyword, or Narcissus is already available in the global scope, or Narcissus already defined in the scope of this function.

Then we define it as a Narcissus object inside an anonymous function.

I can’t tell you why it does this, but it looks like it might already be inside the area where this refers to the object, and it wants to set the hostGlobal key to the global object, and not to the object’s realm now.

This is why it runs it as an anonymous function, since they are not executed in the global scope. Therefore, in its code, hostGlobal: this refers to a global object.

Of course, he could just use hostGlobal: window if this code also fails to run in non-browser environments like node.js, where the global object is global not window . Therefore, he could do this as a very unintuitive method of achievement.

 hostGlobal: ( global === undefined )? window : global 

Hope this helps

0
source

Source: https://habr.com/ru/post/893963/


All Articles