HTML and CSS Reference
In-Depth Information
"undefined undefined"
We will now write an
extends
function that accepts this object as a parameter, and returns
a new object with this object set as its prototype:
function extend(obj) {
function E(){};
E.prototype = obj;
return new E();
}
This code may look unfamiliar or mysterious. That is because this function is taking ad-
vantage of a special type of function we have not seen before called a constructor function.
The first line of this function declares a function called
E
:
function E(){};
By convention constructor functions always start with a capital letter. This is because there
is nothing different between a regular function, a method, and a constructor function ex-
cept (you guessed it) the meaning of the special
this
variable, and the fact that a constructor
function implicitly returns a new object.
On the next line, we set the prototype for the
E
constructor function:
E.prototype = obj;
This means that anytime we use the
E
constructor function to create a new object, it will
implicitly set the passed in object to be its prototype, and therefore it will have access to all
the functionality defined in that prototype.
Constructor functions are the closest JavaScript has to classes. They must be called with
the
new
keyword, and as a result will construct an object that is implicitly returned when
the constructor finishes. Before finishing our look at the
extends
function, it is worth learn-
ing a little more about constructor functions.
Within a constructor function you can use the special
this
variable to set properties on the
implicitly created object. For instance, if we had written the following constructor function:
> function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
you could then construct a person as follows:
> p = new Person('John', 'Smith');