There are lots of ways to create objects in JavaScript and do inheritance, and the creativity usually extrapolates what I consider sane, but these are the ones that I use the most. I will call models here.
And note that this is ES5.
Pseudoclassical
JavaScript is a prototypal, class-free. The pseudoclassical is a way to give JavaScript a feel of the traditional object-oriented languages.
#!/usr/bin/env node
"use strict";
// constructor
var Car = function (name) {
this.name = name;
this.turn_on = function () {
console.log('turn on');
}
}
Car.prototype.get_name = function () {
return this.name;
}
Car.prototype.turn_on = function () {
console.log('push on');
}
// child constructor
var ElectricCar = function (n, bm) {
this.name = n;
this.battery_model = bm;
}
// inherit from Car
ElectricCar.prototype = new Car();
// augment child prototype
ElectricCar.prototype.get_battery_model = function () {
return this.battery_model;
}
// instantiating
var lada = new Car('Lada');
var tesla = new ElectricCar('Tesla');
console.log(lada.name);
console.log(tesla.name);
tesla.turn_on();
Prototypal
The gist below uses Object.create()
. Douglas Crockford, in his book JavaScript: The Good Parts, suggests augmenting Object
in order to create a new object that uses an old object as a prototype. His proposal is:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
}
}
This isn't needed anymore. The book is from 2008. In 2011, ECMAScript 5.1 standardized it.
#!/usr/bin/env node
"use strict";
var lada = {
name: 'Lada',
turn_on: function() {
console.log(this.name + ' on');
},
};
var tesla = Object.create(lada);
tesla.name = 'Tesla';
tesla.recharge = function () {
console.log(this.name + ' battery recharged');
};
console.log(lada.name);
console.log(tesla.name);
tesla.turn_on();
tesla.recharge();
Output
Both should output:
$ node file.js
Lada
Tesla
Tesla on
Tesla battery recharged
$