简体   繁体   中英

ES6 destructure to “this”

Trying ES6 destructuring.

I am using this code in React class constructor:

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

The above code works. But I need the variables in this.class and this.rest .

I have this code and it works:

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

I am looking for something like this:

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

You can use renaming properties, though unfortunately it involves a bit of repetition:

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

classes is the name of the property we're getting off of props ; this.classes is the name of the variable it is getting assigned to. With this.rest , we obviously don't need to name the original property name.

Demo:

 function Foo(props) { ({ classes: this.classes, ...this.rest } = props); } const props = { classes: 'some clases', a: 'A', b: 'B' } console.log(new Foo(props));

One trickier way to achieve is using a function binded with desired this

Here renaming is the key, what happens here is it picks the value from props and assign it to whatever we rename to

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

So this is actually same as

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

You can paste your code here and see simplified version 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)

ray already suggested a way to do this using Object.assign in comments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM