Created
September 20, 2019 14:28
-
-
Save saibotsivad/18e3036f768061966ed0d2ae31d1c7aa to your computer and use it in GitHub Desktop.
javascript forms
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
| class Worker { | |
| constructor(secret) { | |
| // the initializer has access to "secret" | |
| const options = doSomeSetup(secret) | |
| // to give access to other functions, you have to use "this" | |
| this.options = options | |
| this.secret = secret | |
| } | |
| work(parameters) { | |
| // the returned function has access to "this" | |
| // which gives them access to "secret" and "options" | |
| return doSomeWork(this.secret, this.options, parameters) | |
| } | |
| } | |
| // you create and use | |
| const myWorker = new Worker('battery-horse-staple') | |
| console.log(myWorker.work('abc')) // => the results | |
| // but now you have access to "secret" and "options" | |
| console.log(myWorker.secret) // => "battery-horse-staple" | |
| console.log(myWorker.options) // => "abc" |
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 Worker(secret) { | |
| // the initializer has access to "secret" | |
| const options = doSomeSetup(secret) | |
| return { | |
| work: (parameters) => { | |
| // the returned function has access to "options" and "secret" | |
| return doSomeWork(secret, options, parameters) | |
| } | |
| } | |
| } | |
| // you create and use | |
| const myWorker = Worker('battery-horse-staple') | |
| console.log(myWorker.work('abc')) // => the results | |
| // but you don't have access to "secret" or "options" | |
| console.log(myWorker.secret) // => undefined | |
| console.log(myWorker.options) // => undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment