简体   繁体   English

销毁时的参考对象

[英]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. 您可以将create返回值包装在临时外部对象中,然后通过属性名称从外部对象访问原始对象。 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. 这将使用对象的属性a创建变量a ,并创建保存整个对象的变量me

Or, to name it something other than the property name from the outer object (eg, foo instead of me ): 或者,用外部对象的属性名称(例如,用foo代替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. 这可以完全在外部create因此您不必为了使结构易于破坏而仅涉及create函数如何运行的过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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