Overview:
This is a note refer to Top 10 ES6 Features Every Busy JavaScript Developer Must Know, only the parts not familiar with has been attached with code snippets or descriptions.
Extends:
- How Class Implemented In ES5(to be continue)
- Module Define And Import/Export Overview(to be continue)
Content:
- Default Parameters in ES6
- Template Literals in ES6
- Multi-line Strings in ES6
- Destructuring Assignment in ES6
- Enhanced Object Literals in ES6
//ES5
var serviceBase = {port: 3000, url: 'azat.co'},
getAccounts = function(){
return [1,2,3]
}
var accountServiceES5 = {
port: serviceBase.port,
url: serviceBase.url,
getAccounts: getAccounts,
toString: function(){
return JSON.stringify(this.valueOf())
},
getUrl: function(){return "http://" + this.url + ':' + this.port},
valueOf_1_2_3: getAccounts()
}
//ES6
var accountServiceES5ObjectCreate = Object.create(serviceBase)
var accountServiceES5ObjectCreate = {
getAccounts: getAccounts,
toString: function() {
return JSON.stringify(this.valueOf())
},
getUrl: function() {
return "http://" + this.url + ':' + this.port
},
valueOf_1_2_3: getAccounts()
}
-
Arrow Functions in ES6
-
Promises in ES6
ES5
setTimeout(function(){
console.log('Yay!')
setTimeout(function(){
console.log('Wheeyee!')
}, 1000)
}, 1000)
//ES6
var wait1000 = ()=> new Promise((resolve, reject)=> {setTimeout(resolve, 1000)})
wait1000() .then(function() {
console.log('Yay!')
return wait1000()
}) .then(function() {
console.log('Wheeyee!')
})
-
Block-Scoped Constructs Let and Const
-
Classes in ES6
class baseModel {
constructor(options = {}, data = []) { // class constructor
this.name = 'Base'
this.url = 'http://azat.co/api'
this.data = data
this.options = options
}
getName() { // class method
console.log(`Class name: ${this.name}`)
}
}
class AccountModel extends baseModel {
constructor(options, data) {
super({private: true}, ['32113123123', '524214691']) //call the parent method with super
this.name = 'Account Model'
this.url +='/accounts/'
}
get accountsData() { //calculated attribute getter
// ... make XHR
return this.data
}
}
let accounts = new AccountModel(5)
accounts.getName()
console.log('Data is %s', accounts.accountsData)
- Modules in ES6
In node.js, CommonJS literals is supported well, so the writer prefer to use CommonJS in JavaScript, and in below first examples module define are based on CommonJS + Browserify:
//ES5
module.exports = {
port: 3000,
getAccounts: function() {
...
}
}
var service = require('module.js')
console.log(service.port) // 3000
//ES6
export var port = 3000
export function getAccounts(url) {
...
}
import {port, getAccounts} from 'module'
console.log(port) // 3000
import * as service from 'module'
console.log(service.port) // 3000
网友评论