Skip to content

Instantly share code, notes, and snippets.

@saibotsivad
Created September 20, 2019 14:28
Show Gist options
  • Select an option

  • Save saibotsivad/18e3036f768061966ed0d2ae31d1c7aa to your computer and use it in GitHub Desktop.

Select an option

Save saibotsivad/18e3036f768061966ed0d2ae31d1c7aa to your computer and use it in GitHub Desktop.
javascript forms
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"
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