JSFiddle - React, Tailwind, and code Playground
JavaScript
let counter = (def) => ({
state: def,
inc: function() {this.state += 1},
dec: function() {this.state -= 1},
getState: function() {return this.state}
})
const number = 10;
const myCounter = counter(number)
myCounter.inc()
myCounter.inc()
console.log(myCounter.getState())
console.log(myCounter.state)
console.log('----')
function counter2(def) {
return {
state: def,
inc: () => this.state += 1,
dec: () => this.state -= 1,
getState: () => this.state
}
}
const myCounter2 = counter(number)
myCounter2.inc()
myCounter2.inc()
console.log(myCounter2.getState())
console.log(myCounter2.state)