Javascript Function Definitions

I was wondering why the Vector variable defined inside this self-executing javascript function does not require var before it? Is this just some other syntax for creating a named function? Does this mean that we cannot pass the Vector as an argument to other functions?

(function() { Vector = function(x, y) { this.x = x; this.y = y; return this; }; //...snip })() 
+4
source share
4 answers

Defining Vector any other way would create it only within the scope of closure; and will not be available outside of closure.

 (function() { var Vector = function(x, y) { this.x = x; this.y = y; return this; }; function Vector() { // blah }; //...snip })() var something = new Vector() // ERROR :< 

Nothing requires the var keyword; using it, defines the scope in which the variable is available. Without using it, the variable is created in the global scope.

+2
source

The design of the code above makes Vector a global variable in the namespace, which may be OK, since it is probably intended to be used as a constructor.

I would not recommend adding to the global namespace, actually look at requirejs its a very good way to work with modular JS.

+3
source

Defining a variable without var makes it global.

+2
source

Vector in this case will be tied to the current this , which will be window . At the very least, the code you submitted does not need the attached self-executing function.

+1
source

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


All Articles