Created
May 9, 2022 17:57
-
-
Save willmtemple/c03af3b58de6fa448a2b010d077a4637 to your computer and use it in GitHub Desktop.
Old-style Inheritance
This file contains hidden or 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
declare class Vehicle { | |
engines: number; | |
ignition(): void; | |
drive(): void; | |
} | |
declare class Car extends Vehicle { | |
wheels: number; | |
} | |
// "Traditional JS Class" `Vehicle` | |
function Vehicle(this: Vehicle) { | |
this.engines = 1; | |
} | |
Vehicle.prototype.ignition = function() { | |
console.log( "Turning on my engine." ); | |
}; | |
Vehicle.prototype.drive = function() { | |
this.ignition(); | |
console.log( "Steering and moving forward!" ); | |
}; | |
// Natural inheritance?? | |
function Car(this: Car) { | |
// More or less equivalent to super() | |
Vehicle.call(this); | |
// now, let's modify our `car` to specialize it | |
this.wheels = 4; | |
// override `Vehicle::drive()` | |
this.drive = function() { | |
Vehicle.prototype.drive.call( this ); | |
console.log( "Rolling on all " + this.wheels + " wheels!" ); | |
}; | |
} | |
Car.prototype = Vehicle.prototype as Car; | |
var myCar = new Car(); | |
myCar.drive(); | |
// Turning on my engine. | |
// Steering and moving forward! | |
// Rolling on all 4 wheels! |
witemple-msft
commented
May 9, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment