Can't assign this in constructor [duplicate]

允我心安 提交于 2019-12-08 16:05:03

问题


I'm trying to merge the props from values into this.

The following throws an error. How can I do this?

this = {...this, ...values}

回答1:


You could extend this with Object.assign method:

class Foo {
  constructor (props) {
    Object.assign(this, props);
  }
}

const foo = new Foo({ a: 1 });
console.log(foo.a); // 1



回答2:


Seeing your use of the spread operator, it looks like you're using a Stage 3 proposal for ECMAScript.

https://github.com/tc39/proposal-object-rest-spread

Try the Object.assign method:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Object.assign(target, ...sources);



来源:https://stackoverflow.com/questions/36897533/cant-assign-this-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!