Last active
June 22, 2021 17:33
-
-
Save scottgamer/60afcc91e5d2aadb77ac6b40c291dcfc to your computer and use it in GitHub Desktop.
classes
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
| import { Helicopter } from "./mixins"; | |
| class Vehicle { | |
| constructor(public color: string) {} | |
| protected honk(): void { | |
| console.log("beep"); | |
| } | |
| } | |
| const vehicle = new Vehicle("orange"); | |
| console.log(vehicle.color); | |
| export class Car extends Vehicle { | |
| constructor(public wheels: number, color: string) { | |
| super(color); | |
| } | |
| private drive(): void { | |
| console.log("driving car"); | |
| } | |
| startDrivingProcess(): void { | |
| this.drive(); | |
| this.honk(); | |
| } | |
| } | |
| const car = new Car(4, "red"); | |
| car.startDrivingProcess(); | |
| // Calling imported helicopter mixin | |
| Helicopter.takeOff(); |
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
| function mixin(sourceObj: any, targetObj: any) { | |
| for (const key in sourceObj) { | |
| // only copy if not already present | |
| if (!(key in targetObj)) { | |
| targetObj[key] = sourceObj[key]; | |
| } | |
| } | |
| return targetObj; | |
| } | |
| const Aircraft = { | |
| engines: 2, | |
| ignition: function () { | |
| console.log("Turning on engine."); | |
| }, | |
| takeOff: function () { | |
| this.ignition(); | |
| console.log("Lifting off"); | |
| }, | |
| }; | |
| export const Helicopter = mixin(Aircraft, { | |
| engine: 1, | |
| takeOff: function () { | |
| Aircraft.takeOff.call(this); | |
| console.log(`Flying on ${this.engine} engine`); | |
| }, | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment