简体   繁体   English

Javascript ES6中对象解构和普通对象分配有什么区别?

[英]What's the difference between object destructuring and normal object assignment in Javascript ES6?

What's the difference between this two code examples (besides the syntax of course)? 这两个代码示例之间有什么区别(除了语法之外)?

EXAMPLE 1: 例1:

var user = {
   name: 'Diego',
   age: 25
}

var {name} = user;

console.log(name); // Diego

EXAMPLE 2: 例2:

var user = {
   name: 'Diego',
   age: 25
}

var name = user.name;

console.log(name); // Diego

Both examples assign the same value. 两个示例都指定了相同的值。 I don't get what's the difference or vantage/advantage of using either. 我没有得到使用其中任何一个的差异或优势/优势。

Let's extend this to multiple properties: 让我们将它扩展到多个属性:

var {foo, bar, baz} = user;

In the traditional syntax, this would be: 在传统语法中,这将是:

var foo = user.foo,
    bar = user.bar,
    baz = user.baz;

So for every property, we have to repeat the object we want to access ( user ) and the name of the property foo = ... .foo . 因此,对于每个属性,我们必须重复我们想要访问的对象( user )和属性foo = ... .foo The new syntax makes it easier to repeat yourself less. 新语法可以更轻松地重复自己。

There's another difference if the object isn't already stored in a variable: 如果对象尚未存储在变量中,则存在另一个差异:

var {foo, bar, baz} = getUser();

Now we can't just do 现在我们不能做到

var foo = getUser().foo,
    bar = getUser().bar,
    baz = getUser().baz;

because each call to getUser might do different things (due to side effects) or just be inefficient (because we're repeating work). 因为每次调用getUser可能会做不同的事情(由于副作用)或只是效率低下(因为我们正在重复工作)。 We'd have to create a new local variable to store the object in, just to initialize the three variables we actually care about. 我们必须创建一个新的局部变量来存储对象,只是为了初始化我们真正关心的三个变量。

There's no effective difference, but destructuring is convenient: 没有有效的区别,但解构很方便:

var user = {
   name: 'Diego',
   age: 25
}

var {name, age} = user;

That declares and initializes both name and age in one statement without redundant mentions of the property names. 它在一个语句中声明并初始化nameage ,而没有多余的属性名称。

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

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