Last active
February 12, 2018 21:59
-
-
Save g-patel/5679da0fe26f20cc0da6 to your computer and use it in GitHub Desktop.
Javascript oop. This example illustrates that es5 constructors and es6 classes are interoperable in an inheritance chain. So es6 classes are sugar syntax, while the prototype based inheritance is still the underlying implementation by the language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Car { | |
constructor (config) { | |
this.make = config.make || 'Unknown'; | |
this.model = config.model || 'Unknown'; | |
} | |
get price() { | |
return this.price; | |
} | |
set price(price) { | |
this.price = price; | |
} | |
print() { | |
console.log(this.make + ' ' + this.model); | |
} | |
static getConstants() { | |
return {one: 1}; | |
} | |
} | |
// | |
function SUV(config) { | |
this.capacity = config.capacity || 2000; | |
SUV.superclass.constructor.call(this, config); | |
} | |
SUV.superclass = Car.prototype; | |
SUV.prototype = Object.create(Car.prototype); | |
SUV.prototype.constructor = SUV; | |
SUV.prototype.print = function () { | |
SUV.superclass.print.apply(this, arguments); | |
console.log('Capacity: ' + this.capacity); | |
} | |
SUV.prototype.carryLuggage = function () { | |
console.log(this.make + ' ' + this.model + ' carrying luggage..') | |
} | |
SUV.prototype.canCarry = function (weight) { | |
return weight <= this.capacity; | |
} | |
// | |
class LuxurySUV extends SUV { | |
constructor(config) { | |
super(config); | |
this.features = config.features || []; | |
} | |
hasFeature(feature) { | |
return this.features.indexOf(feature) >= 0; | |
} | |
carryLuggage() { | |
super.carryLuggage(); | |
console.log('with luxuries on the ride'); | |
} | |
} | |
var crv = new SUV({ | |
make: 'Honda', | |
model: 'CRV', | |
capacity: 3000 | |
}); | |
crv.print(); | |
crv.carryLuggage(); | |
crv.canCarry(5000); | |
var bmwX5 = new LuxurySUV({ | |
make: 'BMW', | |
model: 'X5', | |
capacity: 4000, | |
features: ['leather_seat', 'e_drive'] | |
}); | |
bmwX5.carryLuggage(); | |
console.log(bmwX5.hasFeature('e_drive')); | |
console.log(bmwX5.hasFeature('moon_roof')); | |
console.log(crv instanceof Car); | |
console.log(crv instanceof SUV); | |
console.log(Car.prototype.isPrototypeOf(crv)); | |
console.log(SUV.prototype.isPrototypeOf(crv)); | |
console.log(crv.constructor); | |
console.log(bmwX5.constructor); | |
console.log(bmwX5 instanceof Car); | |
console.log(bmwX5 instanceof SUV); | |
console.log(bmwX5 instanceof LuxurySUV); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment