Skip to content

Instantly share code, notes, and snippets.

@ybiquitous
Created December 22, 2020 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ybiquitous/bfef585b1dfc6cebf4fcd3f93ec54cef to your computer and use it in GitHub Desktop.
Save ybiquitous/bfef585b1dfc6cebf4fcd3f93ec54cef to your computer and use it in GitHub Desktop.
Closure vs Class on JavaScript
// closure
function foo(initial = 0) {
let counter = initial
return {
get counter() { return counter },
increment() { counter += 1 },
}
}
const f1 = foo()
f1.counter //=> 0
f1.increment()
f1.counter //=> 1
// class
class Foo {
constructor(initial = 0) {
this.counter = initial
}
increment() { this.counter += 1 }
}
const f2 = new Foo()
f2.counter //=> 0
f2.increment()
f2.counter //=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment