Objects
The topics are:
Script Objects
Objects are values which do not contain any predefined properties or methods (except the
toString method), but where new ones can be added. A new, empty object can be created using the Object constructor. For example, the following program creates a new object, stores it in the variable
myCar, and adds the properties "name" and "year" to it:
myCar = new Object() // o contains no properties
myCar.name = "Ford"
myCar.year = 1985
Now:
myCar.name −> "Ford"
myCar.year −> 1985
Defining Methods
Since a method is really a property which contains a
function value, defining a method simply consists in defining a regular function, then assigning it to a property.
For example, the following program adds a method "start" to the
myCar object defined in
Script Objects:
function start_engine() {
writeln("vroom vroom\n")
}
myCar.start = start_engine
Now, the expression myCar.start() will call the function defined as start_engine. Note that the only reason for using a different name for the function and for the method is to avoid confusion; we could have written:
function start() {
writeln("vroom vroom\n")
}
myCar.start = start
The this Keyword
Inside methods, the this keyword can be used to reference the calling object. For example, the following program defines a method getName, which returns the value of the name property of the calling object, and adds this method to myCar:
function get_name() {
return this.name
}
myCar.getName = get_name
Inside constructors, this references the object created by the constructor. When used in a non-method context, this returns a reference on the global object. The global object contains variables declared at toplevel, and built-in functions and constructors.
Object Constructor
Objects are created using the following constructor:
Script Object Constructor
Syntax | Effect |
---|
new Object( ) | Returns a new object with no properties. |
User-defined Constructors
In addition to the Object constructor, any user-defined function can be used as an object constructor, using the following syntax:
Script User-defined Constructor
Syntax | Effect |
---|
new function(arg1, ..., argn) | Creates a new object, then calls function(arg1, ..., argn) to initialize it. |
Inside the constructor, the keyword this can be used to make reference to the object being initialized.
For example, the following program defines a constructor for cars:
function Car(name, year) {
this.name = name
this.year = year
this.start = start_engine
}
Now, calling
new Car("Ford", "1985")
creates a new object with the properties name and year, and a start method.
Built-in Methods
The only object built-in method is:
Script Built-in Method
Syntax | Effect |
---|
object.toString( ) | Returns the string "[object Object]". This method can be overridden by assigning the toString property of an object. |
Published date: 05/24/2022
Last modified date: 02/24/2022