如何在ES2015中将所有属性解构为当前范围/闭包?

问题描述 投票:17回答:2

I'd like to do something like this:

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

const {*} = vegetableColors;

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

我似乎无法找到或弄清楚如何做到这一点,但我真的以为我以前见过它! :P

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

背景:我想在JSX干燥,而不是到处都参考this.statethis.props。如果数据发生变化,也不必继续为destructure添加属性。

javascript ecmascript-6 destructuring ecmascript-7
2个回答
13
投票

我想你正在寻找with statement,它完全符合你的要求:

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

但是,它被弃用(在严格模式下,包括ES6模块),这是有充分理由的。

将所有属性解构为当前范围

你不能在ES61。 And that's a good thing。明确你要引入的变量:

const {corn, peas} = vegetableColors;

或者,您可以使用Object.assign(global, vegetableColors)扩展全局对象以将它们放在全局范围内,但实际上,这比with语句更糟糕。

1:......虽然我不知道在ES7中是否有草案允许这样的事情,但我可以告诉你任何提案都会被TC核实:-)


2
投票

我想你正在寻找:

const {corn, peas} = vegetableColors;

Live on Babel's REPL


如果Pointy's right你问如何在不知道名字cornpeas的情况下这样做,你就不能进行解构赋值。

您只能在全局范围内使用循环,但我确定您不希望在全局范围内执行此操作。不过,以防万一:

// I'm sure you don't really want this, just being thorough
Object.keys(vegetableColors).forEach((key) => {
    Object.defineProperty(this, key, {
        value: vegetableColors[key]
    });
});

(如果你想让这些伪常数可以枚举的话,就把enumerable: true放在那里。)

这适用于全球范围,因为this指的是全局对象。

© www.soinside.com 2019 - 2024. All rights reserved.