javascript - ES6: Destructure methods from class/function? -


i'm wondering if it's possible destructure properties/methods instance of class or function while maintaining scope across destructured variables? 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) 

js bin

the result each console.log same: {count: 0} because it's creating new instance , new scope each of variables.

is intentional? approaching wrong way? (i'm creating library , assume try use way want make work)

in example, destructuring desugars like

const state = counter.state; 

assigning new value counter.state won't magically update value of state. destructuring doesn't change that.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -