Java Reference
In-Depth Information
Constructor Functions
In the
objects chapter
earlier in the topic, we saw that it was possible to create new objects
using the object literal notation. At the end of the chapter we created a
dice
object:
var dice = {
sides: 6;
roll: function () {
return Math.floor(this.sides * Math.random() + 1)
}
}
Another way to create objects is to use a
constructor function
, which is a function that re-
turns an
instance
of an object that's defined in the function when it's invoked with the
new
operator. These are useful because they can be used to create instances of objects over and
over again. This is similar to writing a class in a classical programming language.
Here is the
dice
example rewritten as a constructor function:
var Dice = function(){
"use strict";
this.sides = 6;
this.roll = function() {
return Math.floor(this.sides * Math.random() + 1)
}
}
By convention, the names of constructor functions are capitalized, which is the convention
used for classes in classical programming languages. A constructor function works in a sim-
ilar way to a class, as it can be used to create lots of instances of the same object with all the
properties encapsulated inside. The keyword
this
is used to represent the object that will
be returned by the constructor function. In the previous example, we use it to set the
sides
property to
6
and create a method called
roll
. Each new object that's created using this
constructor function will inherit these properties and methods.
