如何在 ES2015 中将所有属性解构为当前范围/闭包? [英] How do I destructure all properties into the current scope/closure in ES2015?
问题描述
我想做这样的事情:
const steelColors = {corn: 'yellow', peas: 'green'};const {*} = 蔬菜颜色;console.log(corn);//黄色console.log(peas);//绿色
我似乎无法找到或弄清楚如何做到这一点,但我真的以为我以前在某个地方见过它!:P
注意:我将 Babel 与 stage
一起使用设置为 0
;
上下文:我试图在 JSX 和不要到处引用 this.state
或 this.props
.如果数据发生变化,也不必继续添加属性来解构.
我认为您正在寻找 with
声明,它完全符合您的要求:
const steelColors = {corn: 'yellow', peas: 'green'};与(蔬菜颜色){console.log(corn);//黄色console.log(peas);//绿色}
但是,它被弃用(在严格模式下,包括 ES6 模块),这是有充分理由的.
<块引用>将所有属性分解为当前作用域
你不能在 ES61 中.这是一件好事.明确说明您要引入的变量:
const {corn, peas} = 蔬菜颜色;
或者,您可以使用 Object.assign(global,vegetableColors)
扩展全局对象以将它们放在全局范围内,但实际上,这比 with
更糟糕声明.
1:……虽然我不知道 ES7 中是否有允许这样的东西的草案,但我可以告诉你,任何提案都会被 TC 否决:-)>
I'd like to do something like this:
const vegetableColors = {corn: 'yellow', peas: 'green'};
const {*} = vegetableColors;
console.log(corn);// yellow
console.log(peas);// green
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
NOTE: I'm using Babel with stage
set to 0
;
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.
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
}
However, it is deprecated (in strict mode, which includes ES6 modules), for good reason.
destructure all properties into the current scope
You cannot in ES61. And that's a good thing. Be explicit about the variables you're introducing:
const {corn, peas} = vegetableColors;
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: … and while I don't know whether there is a draft to allow such things in ES7, I can tell you that any proposal will be nuked by the TC :-)
这篇关于如何在 ES2015 中将所有属性解构为当前范围/闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!