Here is how I would write your code:
function Vehicle (name, options) {
this.name = name
this.wheels = options.wheels
this.passengers = options.passengers
}
Vehicle.prototype.makeNoise = function () {
console.log('vroom')
return this
}
var bus = new Vehicle('bus', { wheels: 4, passengers: 10 })
bus.pickUpPassengers = function (toPickUp) {
this.passengers += toPickUp
return this
}
bus.pickUpPassengers(5)
This uses JavaScript's prototypical inheritance, which can be used like classes in other languages. Constructors start with a capital letter (by convention) and are called with new
. Using prototypes also means that you don't define methods like makeNoise
every time you create a new vehicle, instead all the vehicles refer back to the prototype.
I've also used return this
at the end of the methods as it allows chaining:
// Without chaining:
foo.bar()
foo.baz()
foo.qux()
// With chaining:
foo.bar().baz().qux()
The Vehicle constructor also takes the numbers of wheels and passengers in an options object, which makes it easier to read and understand what the numbers are for.
With ES6 it would look like this:
class Vehicle {
constructor (name, { wheels, passengers } = {}) {
this.name = name
this.wheels = options.wheels
this.passengers = options.passengers
}
makeNoise () {
console.log('vroom')
return this
}
}
class Bus extends Vehicle {
constructor (options) {
super('bus', options)
}
pickUpPassengers (toPickUp) {
this.passengers += toPickUp
return this
}
}
const bus = new Bus({ wheels: 4, passengers: 10 })
bus.pickUpPassengers(10)
(Here I chose to make Bus
a subclass of Vehicle
because it's easier with ES6. It also helps you if you want to create more than one bus.)