Created
December 22, 2020 02:57
-
-
Save ybiquitous/bfef585b1dfc6cebf4fcd3f93ec54cef to your computer and use it in GitHub Desktop.
Closure vs Class on JavaScript
This file contains 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
// 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