简体   繁体   中英

Reference object when destructuring

I'm playing with destructuring:

function create(){
 let obj={a:1,b:2}
obj.self=obj
 return obj
}
const {a,self} = create()

Is there a way to get the self object without adding such a property ?

function create(){
 let obj={a:1,b:2}
// removes   obj.self=obj
 return obj
}
const {a,this} = create()

In one line of code if possible!

Thank you in advance for your help.

You can wrap your create return value inside a temporary outer object, and then access the original object by property name from the outer object. This still allows you to pull out properties from the original object as well.

const {me:{a}, me} = {me:create()}

This will create the variable a using the property a from the object, and create the variable me which holds the entire object.

Or, to name it something other than the property name from the outer object (eg, foo instead of me ):

const {me:{a}, me:foo} = {me:create()}

This still requires making an additional property, but the property exists on the instantly-disposed wrapper object. This can be done entirely external to create so you don't need to touch the process of how the create function operates just to make it destructuring-friendly.

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