官术网_书友最值得收藏!

Object literals

ES6 makes some improvements to object literals. There are several improvements, but the one you'll see most is the implicit naming of object properties. In ES5 it would be as follows:

var name = ‘Burak’;
var title = ‘Author’;
var object = {name: name, title: title};

In ES6, if the property name and the variable name are the same as the preceding one, you can simplify it to the following:

const name = ‘Burak’;
const title = ‘Author’;
const object = {name, title};

Additionally, ES6 introduces the object spread operator, which simplifies shallow object merges. For instance, take a look at the following code in ES5:

function combinePreferences(userPreferences) {
var defaultPreferences = {size: ‘large’, mode: ‘view’};
return Object.assign({}, defaultPreferences, userPreferences);
}

The preceding code will create a new object from defaultPreferences, and merge in properties from userPreferences. Passing an empty object to the Object.assign instance first parameter ensures that we create a new object rather than overwriting defaultPreferences (which isn't an issue in the preceding example, but is an issue in real-life use cases).

And now, let's take a look at the same in ES6:

function combinePreferences(userPreferences) {
var defaultPreferences = {size: ‘large’, mode: ‘view’};
return {...defaultPreferences, ...userPreferences};
}

This approach does the same as the ES5 example, but is quicker and easier to read in my opinion than the Object.assign method. Developers familiar with React and Redux, for instance, often use the object spread operator when managing reducer state operations.

主站蜘蛛池模板: 合水县| 淮南市| 大城县| 绥中县| 吉安县| 松滋市| 汤阴县| 乌拉特前旗| 柳河县| 肇东市| 伊宁县| 濮阳县| 乌兰浩特市| 社会| 贵阳市| 扶沟县| 迁西县| 象州县| 大宁县| 榆林市| 胶州市| 麟游县| 肃宁县| 海丰县| 门头沟区| 兴宁市| 托里县| 西昌市| 临西县| 福州市| 新兴县| 浠水县| 三亚市| 普宁市| 德庆县| 宣恩县| 定陶县| 凤凰县| 曲松县| 奉新县| 荔浦县|