Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  158] [ 6]  / answers: 1 / hits: 24358  / 8 Years ago, thu, february 4, 2016, 12:00:00

I am currently learning Javascript and I noticed something that, to me, doesn't make much sense.



In an example on the ArcGIS website, there is this piece of code



var map
require([esri/map, dojo/domReady!], function(Map) {
map = new Map(mapDiv, {
center: [-56.049, 38.485],
zoom: 3,
basemap: streets
});
});


I don't get how you can do new Map when Map is the parameter of function(Map). To be able to use new, then Map must be a type and I haven't seen a type being a parameter in other languages.


More From » javascript

 Answers
6

The funny thing about Javascript is that there really are no classes. The equivalent of a class in Javascript is just a special kind of function. Actually, forget about the special in the previous sentence (just wanted to soften the blow). Any function can act as a class and be instantiated with the new operator (although it is really only useful when that function assigns stuff to this so the generated object gains public methods and attributes).



And functions in Javascript are first-class citizens. Functions can be assigned to variables and functions can be passed as arguments to other functions. This makes it perfectly legal to pass a function to another function and then have that other function instantiate it with new.



Yes, this is indeed a very strange concept to wrap a head around which is used to class-oriented programming languages. But it becomes surprisingly intuitive once you understand it.



So what happens in the code you posted in the question is this:




  1. When require is executed, it calles an anonymous function passing a class function to it

  2. the anonymous function assigns that class function to a local variable Map

  3. the anonymous function then creates an instance of that class function.

  4. the instance is assigned to the global variable map


[#63444] Tuesday, February 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cullenmaxl

Total Points: 414
Total Questions: 112
Total Answers: 87

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;