在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)?
var user = {
name: 'Diego',
age: 25
}
var {name} = user;
console.log(name); // Diego
示例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;
因此,对于每个属性,我们都必须重复要访问的对象(user
)和属性foo = ... .foo
的名称.新语法使重复次数减少了.
So for every property, we have to repeat the object we want to access (user
) and the name of the property 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();
现在我们不能只是做
var foo = getUser().foo,
bar = getUser().bar,
baz = getUser().baz;
因为每次调用getUser
可能会做不同的事情(由于副作用)或效率低下(因为我们正在重复工作).我们必须创建一个新的局部变量来存储对象,仅用于初始化我们实际关心的三个变量.
because each call to getUser
might do different things (due to side effects) or just be inefficient (because we're repeating work). We'd have to create a new local variable to store the object in, just to initialize the three variables we actually care about.
这篇关于在Javascript ES6中,对象解构和常规对象分配之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!