instantiating using pseudoclassical style (using .call or .apply)
Constructor functions have two key uses:
1. To generate new instances with common properties (if utilizing the 'new' keyword at call time)
2. To assign new properties to a focal object (without the 'new' keyword)
In the example below, we can use the Flower
function to create multiple instances of the Flower
object, each with a different color property. To call the constructor:
var rose = new Flower('pink');
var clover = new Flower('green');
The outcome of these two lines will result in two new Flower instances being created:
rose = {
color: 'pink',
height: 0
}
clover = {
color: 'green',
height: 0
}
To demonstrate the second purpose of Constructor functions, we have added a subclass relationship between Flower
and Lotus
(that is, Lotus
is a subclass of Flower
). How did we initialize this subclass relationship, and what is its outcome?
Remember that the second purpose of constructors is to add properties to a focal object. That's what we are doing here. We call the built-in .call
or .apply
methods of Flower
on the instance of Lotus
by identifying the instance properly as this.
Passing the Lotus instance into the Flower.call( this, color )
will result in us setting the color and height properties for each Lotus
instance. What we've done is make use of the helper-like qualities of the constructor Flower
to avoid duplicate code and have all Lotus
instances receive a set of common properties.
Example Code:
var Flower = function ( color ) {
this.color = color;
this.height = 0;
};
Flower.prototype.grow = function ( ) {
this.height++;
};
var Lotus = function ( color ) {
// this = Object.create(Lotus.prototype);
Flower.call( this, color );
// return this;
}
Lotus.prototype = Object.create(Flower.prototype);
Lotus.prototype.constructor = Lotus;
var blueLotus = new Lotus( 'blue' );