The following syntax defines an anonymous function object.
Function objects can be defined anywhere, even inside another function. They can be used like any other object: they can be assigned to variables and passed as parameters. They can even have their own instance variables and methods! This allows a function to serve as the constructor method for a class of objects3.
The example below assigns the above function to a local
This is equivalent to the more usual function definition below.
Local variables in a function can be declared with the
var is not required here -
However, if the keyword
var is omitted
the variable is global!
This can produce errors that are very hard to debug.
If the receiver is omitted the the implied
receiver is the
window object is, in effect, global.
There are no other implicit receivers, even inside
code for a class!
In Java, this conversion is called autoboxing. In either language, it allows primitive values to be treated as if they are objects.
A single anonymous object can be created with a comma-separated list of member definitions enclosed in braces. Each member definition has the following form.
Both instance variables and methods can be defined in this way. For methods, the value is often an anonymous function definition, but can also refer to a previously defined function.
Thus the general form of an anonymous object is the following.
As with functions, an anonymous object can be defined anywhere. It is often assigned to a global variable. When this is done, the object is used like a Java class whose members are all static. The members are accessed by sending a message with the variable as a receiver. The Log class is an example of this kind of construction. The comments indicate the form of messages sent to the Log class object.
A class of objects is defined by defining a variable whose value is the constructor function for the class, and following it with definitions for static and instance members. Static members have the following form.
Instance members have the following form.
As usual, the value can be an anonymous function for static or instance methods.
The Circle class is an example of this kind of construction. The comments indicate the form of messages sent to the Circle class object or one of its instances.
Note that if code in an instance method sends a message
to the instance, the receiver is specified with the
this the default
Omitting the keyword
this results in
sending the message to the global