You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// extract states from an object to local variablesconst{a, b =0, ...rest}=obj// assign states from local variables to objectObject.assign(obj,{a, b})// use enumeration to assign "safely"for(constkeyinobj)obj[key]=rest[key]
class{abconstructor(obj){// destructuring to class instance is awkwardletrest{a: this.a,b: this.b, ...rest}=obj// use assignconst{a, b =0, ...rest}=objObject.assign(this,{a, b})// or use enumeration// WARN: may miss accessors on prototype and include conventional private `_foo`for(constkeyinthis){this[key]=rest[key]}}}
class{
#a
#b
constructor(obj){// destructuring to class instance is awkwardletrest{a: this.#a,b: this.#b, ...rest}=obj// no way to assignconst{a, b =0, ...rest}=objObject.assign(this,{#a: a, #b: b})// illegal!// no way to enumeratefor(constprivinthis.#){// illegalthis.#[priv]=rest[key]// illegal}}}
class{
#$
constructor(obj){// destructingconst{a, b, ...rest}=objthis.#$ ={a, b}// use assignconst{a, b =0, ...rest}=objObject.assign(this.#$,{a, b})// or use enumerationfor(constkeyinthis.#$){this.#$[key]=rest[key]}}geta(){returnthis.#$.a// access private become a little weird}b(...args){this.#$.b.call(this, ...args)// rebind this 😥}}
How classes 2.0 solve the problem:
class{myamybconstructor(obj){// destructingletrest{a,b, ...rest}=obj// no need to use assign because destructing just work// but still possible{// use block for shadowingconst{a, b =0, ...rest}=objObject.assign(this,{[private.a]: a,[private.b]: b,})}// or use enumerationfor(const[name,privateKey]ofObject.entries(private.this)){this[privateKey]=rest[name]}}}