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.
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:
require
is executed, it calles an anonymous function passing a Map
map
To be able to use new, then Map must be a type
No. For new
to work, Map
must be a function.
Functions are first class objects in JavaScript and can be treated like any other piece of data (assigned to variables, passed as function arguments, etc).
function One() {
this.foo = 1;
}
function myCallingThing(arg) {
alert(new arg().foo + 1);
}
var Two = One;
var instance = new Two;
alert(instance.foo);
myCallingThing(Two);
This is not unique to JavaScript.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
sub example {
say "Hello";
}
sub callme {
my $var = shift;
$var->();
}
callme(\&example);
or
#!/usr/bin/python
def example():
print "Hello\n"
def callme(arg):
arg();
callme(example)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With