You can do it without any additional libraries - it's just slightly more long-winded.
jsFiddle
First set up a car
class and give it some methods (setColor
, setMake
and setModel
):
function car(make,model){
console.log( 'car constructor' );
this.setMake( make );
this.setModel( model );
}
car.prototype.setColor = function(color){ this.color = color; };
car.prototype.setMake = function(make ){ this.make = make; };
car.prototype.setModel = function(model){ this.model = model; };
car.prototype.toString = function(){ return 'This is a ' + this.color + ' ' + this.make + ' ' + this.model + ' car' };
Then you can inherit from the car:
function volvo( model ){
console.log( 'volvo constructor' );
car.call( this, 'volvo', model );
}
volvo.prototype = Object.create( car.prototype );
volvo.prototype.constructor = volvo;
Looking at the various sections then:
function volvo( model ){}
defines a volvo
class.
- And within the constructor
car.call( this, 'volvo', model );
is used to call the constructor of the parent class with a fixed make of volvo
.
volvo.prototype = Object.create( car.prototype );
sets the volvo
class to inherit from the car
class.
volvo.prototype.constructor = volvo;
is used to ensure that the volvo
class uses the volvo
constructor (without this line the previous statement would cause it to use the car
constructor).
We can then test this:
var c = new car('Ford', 'Fiesta');
c.setColor('Red');
console.log( c.toString() );
var v = new volvo( 'S10' );
v.setColor( 'Grey' );
console.log( v.toString() );
The output is (including the log entries showing when the constructors were called):
car constructor
This is a Red Ford Fiesta car
volvo constructor
car constructor
This is a Grey volvo S10 car
And if you need a polyfill for Object.create
then you can use:
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o
return new F()
}
})()
}