ES6用于解构和分配对象属性的好东西

时间:2017-11-12 11:15:49

标签: javascript ecmascript-6 destructuring

我是一名软件开发人员,现在学习新的ES6风格的JavaScript 。我发现ES6功能很棒,但我还没有发现ES6提供的所有最流行的功能,我发现在实践中很难明智地使用它。

我有以下代码行 - 如果可能且实用 - 我想更简单。我必须承认,在这个例子中,我也只是为了重构而重构并且更好地学习ES6如何帮助我在将来创建富有表现力的简单代码(或者至少可以理解是否有人使用一些疯狂的单线)。

// HTML: <canvas></canvas>
const canvas = document.querySelector('canvas');
// I'm wondering if there is another way to do this:
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

我可以像这样创建widthheight

const { innerWidth: width, innerHeight: height } = window;
// equivalent to:
const width = window.innerWidth;
const height = window.innerHeight;

我正在寻找一种解决方案,而不是创建新变量,使用一些属性名称将值分配给对象。 是否有惯用的方法来执行此操作?

这样的事情:

const canvas = document.querySelector('canvas');
// NONE OF THESE WORKED
const { innerWidth: canvas.width, innerHeight: canvas.height } = window;
const { canvas.width, canvas.height } = { window.innerWidth, window.innerHeight }

2 个答案:

答案 0 :(得分:2)

  

这样的事情:

// NONE OF THESE WORKED
const { innerWidth: canvas.width, innerHeight: canvas.height } = window;

这是正确的方法。但是,您不希望声明新变量,而是将canvas属性作为目标,因此const在这里是错误的。您只需要分配。 you need to wrap in parenthesis

({ innerWidth: canvas.width, innerHeight: canvas.height } = window);

答案 1 :(得分:1)

在一行中执行此操作而不编写极难读取的代码的一种可能方法是使用数组解构(当属性名称与源和目标对象不同时)。

[canvas.width, canvas.height] = [window.innerWidth, window.innerHeight]