ES6 解构为 "this"

ES6 destructure to "this"

尝试 ES6 解构。

我在 React class 构造函数中使用此代码:

let { class, ...rest } = props;

以上代码有效。但是我需要 this.classthis.rest 中的变量。

我有这段代码并且有效:

let { classes, ...rest } = props; 
this.classes = classes; 
this.rest = rest; 

我正在寻找这样的东西:

{ this.classes, ...this.rest } = props;  

一种更棘手的实现方法是使用与所需 this

绑定的函数

这里重命名是关键,这里发生的是它从 props 中选取值并将其分配给我们重命名的任何内容

({ classes:this.classes,...this.rest } = props)

所以这实际上与

相同
this.classes = props.classes;
this.rest = all the properties expect those which are already destrucutred

您可以在此处粘贴您的代码并查看简化版本Babel


const props = {
  classes: 'some clases',
  a: 'A',
  b: 'B'
}

let tempThis = {}
console.log(tempThis)

let getMeValuesOnThis = function(props) {
  ({ classes:this.classes,...this.rest } = props)
}.bind(tempThis)

getMeValuesOnThis(props)

console.log('---values after function execution---')
console.log(tempThis)

已经在评论

中提出了使用 Object.assign 的方法

您可以使用重命名属性,但不幸的是它涉及到一些重复:

({ classes: this.classes, ...this.rest } = props);

classes 是我们从 props 下车的 属性 的名字; this.classes 是它被分配给的变量的名称。有了this.rest,我们显然不需要命名原来的属性名字了

演示:

function Foo(props) {
    ({ classes: this.classes, ...this.rest } = props);
}

const props = {
  classes: 'some clases',
  a: 'A',
  b: 'B'
}

console.log(new Foo(props));