最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - What's the difference between object destructuring and normal object assignment in Javascript ES6? - Stac

programmeradmin5浏览0评论

What's the difference between this two code examples (besides the syntax of course)?

EXAMPLE 1:

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

var {name} = user;

console.log(name); // Diego

EXAMPLE 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.

What's the difference between this two code examples (besides the syntax of course)?

EXAMPLE 1:

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

var {name} = user;

console.log(name); // Diego

EXAMPLE 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.

Share Improve this question asked Feb 18, 2017 at 14:31 Diogo CapelaDiogo Capela 6,5705 gold badges28 silver badges37 bronze badges 1
  • 2 Destructuring is a handy shortcut when you have an object that contains many other things, and you want to "pull out" many values at once. – Carcigenicate Commented Feb 18, 2017 at 14:33
Add a ment  | 

2 Answers 2

Reset to default 15

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. 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). 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论