I'm wondering if it's possible to destructure the properties/methods from an instance of a class or function while maintaining scope across the destructured variables? For example:
function Counter() {
this.state = {count: 0}
this.update = (fragment) => {
this.state = Object.assign({}, this.state, fragment)
}
this.increment = () => {
this.update({count: this.state.count + 1})
}
this.decrement = () => {
this.update({count: this.state.count - 1})
}
}
const counter = new Counter
const {
state,
increment,
decrement
} = counter
console.log(state)
increment()
console.log(state)
decrement ()
console.log(state)
The result for each console.log is the same: {count: 0}
because it's creating a new instance and new scope for each of the variables.
Is this intentional? Am I approaching this the wrong way? (I'm creating a library and I assume someone will try to use it this way so I want to make it work)