ELOQUENT JS -- CONTENTS
Just like the notation with braces and colons we have already seen,
new
is a way to create object values. Instead of specifying all the property names and values, a function is used to build up the object. This makes it possible to define a kind of standard procedure for creating objects. Functions like this are called constructors, and in chapter 8 we will see how to write them.
The
new
keyword provides a convenient way of creating new objects. When a function is called with the wordnew
in front of it, itsthis
variable will point at a new object, which it will automatically return (unless it explicitly returns something else). Functions used to create new objects like this are called constructors. Here is a constructor for rabbits:
function Rabbit(adjective) {
this.adjective = adjective;
this.speak = function(line) {
print("The ", this.adjective, " rabbit says '", line, "'");
};
}
var killerRabbit = new Rabbit("killer");
killerRabbit.speak("GRAAAAAAAAAH!");
It is convention to start the names of constructors with a capital letter. This makes it easy to distinguish them from other functions.