所有属性如何在ES2015的当前范围/关闭中进行重组? [英] How do I destructure all properties into the current scope/closure in ES2015?

查看:109
本文介绍了所有属性如何在ES2015的当前范围/关闭中进行重组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const vegetableColors = {corn: 'yellow', peas: 'green'};

const {*} = vegetableColors;

console.log(corn);// yellow
console.log(peas);// green

我似乎找不到或弄清楚如何做到这一点,但我真的以为我以前曾经看过它! :P

I can't seem to find or figure out how to do this but I really thought I had seen it done somewhere before! :P

注意:我正在使用 Babel stage 设置为 0 ;

NOTE: I'm using Babel with stage set to 0;

CONTEXT:我试图在 JSX 中变干引用 this.state this.props 无处不在。如果数据发生变化,也不必继续添加属性进行重组。

CONTEXT: I'm trying to be drier in JSX and not reference this.state or this.props everywhere. And also not have to keep adding properties to destructure if the data changes.

推荐答案

我想你在寻找 with 声明,它正是您要求的:

I think you're looking for the with statement, it does exactly what you are asking for:

const vegetableColors = {corn: 'yellow', peas: 'green'};
with (vegetableColors) {
    console.log(corn);// yellow
    console.log(peas);// green
}

但是,这是不推荐使用(严格模式,包括ES6模块) p>

However, it is deprecated (in strict mode, which includes ES6 modules), for good reason.


将所有属性重新整理到当前范围

destructure all properties into the current scope

您不能在ES6 1 这是一件好事。明确你介绍的变量:

You cannot in ES61. And that's a good thing. Be explicit about the variables you're introducing:

const {corn, peas} = vegetableColors;

或者,您可以使用 Object.assign(global,蔬菜科学家)将它们放在全球范围内,但实际上比语句更差。

Alternatively, you can extend the global object with Object.assign(global, vegetableColors) to put them in the global scope, but really, that's worse than a with statement.

1:...虽然我不知道是否有一个草案在ES7中允许这样的事情,我可以告诉你,任何提案将被TC禁止: - )

这篇关于所有属性如何在ES2015的当前范围/关闭中进行重组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆