Reference object on destruction

I am playing with destruction:

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!

Thanks in advance for your help.

+3


source to share


1 answer


You can wrap the return value create

in a temporary external object and then access the original object by the property name from the external object. This still allows properties to be pulled from the original object.

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

      

This will create a variable a

using a property a

from the object and create a variable me

that contains the entire object.



Or, to call it something other than a property name from an external object (for example, foo

instead of me

):

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

      

This still requires an additional property to be created, but the property exists on the instantly allocated wrapper object. This can be made completely external to create

, so you don't have to touch the function's flow create

to make it destructible.

+2


source







All Articles