- Hands-On Machine Learning with JavaScript
- Burak Kanber
- 269字
- 2021-06-25 21:38:19
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.
- 西門子S7-200 SMART PLC從入門到精通
- 智能工業(yè)報警系統(tǒng)
- Maya極速引擎:材質(zhì)篇
- 新手學(xué)電腦快速入門
- RPA(機器人流程自動化)快速入門:基于Blue Prism
- 變頻器、軟啟動器及PLC實用技術(shù)260問
- Learning Azure Cosmos DB
- Linux嵌入式系統(tǒng)開發(fā)
- Mastering Ansible(Second Edition)
- 數(shù)字多媒體技術(shù)與應(yīng)用實例
- 分布式Java應(yīng)用
- Spark Streaming實時流式大數(shù)據(jù)處理實戰(zhàn)
- Building Impressive Presentations with Impress.js
- SQL Server 2017 Machine Learning Services with R
- 從虛擬化到云計算