Learn New Features in ES 2015 Part 4
学习ES2015 Part 4
New Features of Object
Shorthand syntax
ES2015 has such a syntactic sugar that when a new Object is generated, it can have a shorthand when the key name is the same as the variable name. See the following example for exactly how to write it.
In the past, we needed to write it like this:
function buildUser(first, last) {
var fullName = first + ' ' + last;
return { first: first, last: last, fullName: fullName };
}
The return part of the function above seems very cumbersome, we can now write it like this:
function buildUser(first, last) {
let fullName = `${first} ${last}`;
return { first, last, fullName };
}
In this example, we also combine what we talked about in the previous sections:
Using
let
instead ofvar
for variable declarationUsing Template String instead of string splicing
Using Object's Shorthand writing style
When the property of an Object is a method, we can use a similar syntax, for example, we write function like this (Shorthand syntax and non-Shorthand syntax can be mixed)
function buildUser(first, last) {
let fullName = `${first} ${last}`;
const ACTIVE_POST_COUNT = 10;
return {
first,
last,
fullName,
isActive: function() {
return postCount >= ACITVE_POST_COUNT;
}
};
}
We can omit the function
keyword and just use the method name:
function buildUser(first, last) {
let fullName = `${first} ${last}`;
const ACTIVE_POST_COUNT = 10;
return {
first,
last,
fullName,
isActive() {
return postCount >= ACITVE_POST_COUNT;
}
};
}
Object Destructing
This feature is very similar to Array's Destructing, when we only need part of an Object's properties, we no longer need to fetch them one line at a time. In ES5:
let user = buildUser('Hegwin', 'Wang');
let first = user.first;
let last = user.last;
let fullName = user.fullName;
In ES2015, it would then look like this:
let user = buildUser('Hegwin', 'Wang');
let { first, last, fullName } = user;
We can do this as long as the variable name to be assigned is the same as the property name of the Object. Also, we can take only some of the properties:
let user = buildUser('Hegwin', 'Wang').
let { last, fullName } = user.
Using Object.assign
If we need to merge multiple Objects, for example in a function, and we need to override the default configuration with the values in the parameters, in this scenario we might use a third-party provided method like jQuery.extend( target [, object1 ] [, objectN ] )
, and now Object.assign
does just that. An example:
function countdownTimer(target, timeLeft,options={}) {
let defaults = {
// default options here ...
};
let settings = Object.assign({}, defaults, options);
// rest codes ...
}
Note: For the first parameter of Object.assign
above, we pass an empty Object, in case defaults
is overwritten and can't be used anymore.