Created
August 31, 2025 22:45
-
-
Save ianjosephwilson/8da6209754799f0e030b381da9a67d57 to your computer and use it in GitHub Desktop.
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 createEngineFactory(radiusDefault) { | |
| /* | |
| Class methods. | |
| */ | |
| function turnOn(self) { | |
| self.running = true; | |
| } | |
| function turnOff(self) { | |
| self.running = false; | |
| } | |
| function setRadius(self, radius) { | |
| self.radius = parseInt(radius, 10); | |
| } | |
| function printStatus(self) { | |
| console.log(`STATUS: Engine is ${self.running ? 'on' : 'off'} and radius is ${self.radius}`); | |
| } | |
| return function () { | |
| // Define data. | |
| let self = { | |
| running: false, | |
| radius: radiusDefault, | |
| }; | |
| // Bind methods as partials of classmethods with self as the first argument. | |
| // Just ignoring `this` completely right now. | |
| self.turnOn = function () { turnOn.call(null, self) }; | |
| self.turnOff = function () { turnOff.call(null, self) }; | |
| self.setRadius = function (radius) { setRadius.call(null, self, radius) }; | |
| self.printStatus = function () { printStatus.call(null, self) }; | |
| return function (msg) { | |
| if (msg === 'turnOn') { | |
| self.turnOn(); | |
| } else if (msg === 'turnOff') { | |
| self.turnOff(); | |
| } else if (msg === 'setRadius') { | |
| self.setRadius(arguments[1]); | |
| } else if (msg === 'printStatus') { | |
| self.printStatus(); | |
| } else { | |
| throw `Invalid method ${msg}` | |
| } | |
| } | |
| } | |
| } | |
| let Engine = createEngineFactory(15); | |
| let engine1 = Engine() | |
| engine1('printStatus') | |
| engine1('turnOn') | |
| engine1('printStatus') | |
| engine1('turnOff') | |
| engine1('printStatus') | |
| engine1('setRadius', 100) | |
| engine1('printStatus') | |
| let engine2 = Engine() | |
| engine1('turnOn') | |
| engine2('turnOff') | |
| engine1('printStatus'); | |
| engine2('printStatus'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment