Last active
February 26, 2022 09:53
-
-
Save bradoyler/9194612 to your computer and use it in GitHub Desktop.
JS inheritance. Explained.
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
// via http://www.klauskomenda.com/code/javascript-inheritance-by-example/ | |
// create constructor function for base "class" | |
function Vehicle(hasEngine, hasWheels) { | |
this.hasEngine = hasEngine || false; | |
this.hasWheels = hasWheels || false; | |
} | |
// create constructor function | |
function Car (make, model, hp) { | |
this.hp = hp; | |
this.make = make; | |
this.model = model; | |
} | |
// setup inheritance | |
Car.prototype = new Vehicle(true, true); | |
// extend Car with prototype | |
Car.prototype.displaySpecs = function () { | |
console.log(this.make + ", " + this.model + ", " + this.hp + ", " + this.hasEngine + ", " + this.hasWheels); | |
} | |
// New instance of Car | |
var myAudi = new Car ("Audi", "A4", 150); | |
// prove inheritance worked | |
console.log(myAudi.displaySpecs()); // logs: Audi, A4, 150, true, true | |
// extend Vehicle | |
Vehicle.prototype.hasTrunk = true; | |
// show inherited property | |
console.log(myAudi.hasTrunk); // logs: true | |
// another from http://www.objectplayground.com/ | |
// Parent class constructor | |
function Parent() { | |
this.a = 42; | |
} | |
// Parent class method | |
Parent.prototype.method = function method() {}; | |
// Child class constructor | |
function Child() { | |
Parent.call(this); | |
this.b = 3.14159 | |
} | |
// Inherit from the parent class | |
Child.prototype = Object.create(Parent.prototype); | |
Child.prototype.constructor = Child; | |
// Child class method | |
Child.prototype.method = function method() { | |
Parent.prototype.method.call(this); | |
}; | |
// Instantiate | |
this.instance = new Child(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment