1. 默认参数
之前我们使用的默认传参方式:
var link = function (height, color, url) {
var height = height || 50
var color = color || 'red'
var url = url || 'http://azat.co'
...
}
现在es6新语法:
var link = function(height = 50, color = 'red', url = 'http://azat.co') {
...
}
这个不用解释,简单易懂!
2. 字符串拼接
之前我们使用的字符串拼接方式:
var name = 'Your name is ' + first + ' ' + last + '.';
var url = 'http://localhost:3000/api/messages/' + id;
现在es6新语法:
var name = `Your name is ${first} ${last}.`;
var url = `http://localhost:3000/api/messages/${id}`;
使用``反引号,位置在tab的上方,应该也简单易懂!
3. 换行字符串拼接
之前我们使用的字符串拼接方式:
var roadPoem = 'Then took the other, as just as fair,\n\t'
+ 'And having perhaps the better claim\n\t'
+ 'Because it was grassy and wanted wear,\n\t'
+ 'Though as for that the passing there\n\t'
+ 'Had worn them really about the same,\n\t'
var fourAgreements = 'You have the right to be you.\n\
You can only be you when you do your best.'
现在es6新语法:
var roadPoem = `Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear,
Though as for that the passing there
Had worn them really about the same,`
var fourAgreements = `You have the right to be you.
You can only be you when you do your best.`
同样使用``反引号,就不用管换行了!
4. 结构赋值
之前我们使用的赋值方式:
var data = $('body').data(), // data has properties house and mouse
house = data.house,
mouse = data.mouse
现在es6新语法:
var {house, mouse} = $('body').data() // we'll get house and mouse variables
var {json: jsonMiddleware} = require('body-parser')
var {username, password} = req.body
////
var [col1, col2] = $('.column'),
[line1, line2, line3, , line5] = file.split('\n')
5. 对象加强
之前我们使用方式:
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()
}
现在可以继承了!
6. 箭头函数
之前我们使用方式:
var _this = this
$('.btn').click(function(event){
_this.sendData()
})
现在es6新语法:
$('.btn').click((event) =>{
this.sendData()
})
一个箭头就搞定了!
7. Promises
现在es6新语法:
var wait1000 = new Promise(function(resolve, reject) {
setTimeout(resolve, 1000)
}).then(function() {
console.log('Yay!')
})
只是语法上面简单些,更加容易阅读和维护!
8. Let 和 Const
现在es6新语法:
for (var i = 0; i < 10; i++) {}
console.log(i); //10
for (let j = 0; j < 10; j++) {}
console.log(j); //Uncaught ReferenceError: j is not defined
const value = 100;
console.log(value);
value = 200; //Uncaught TypeError: Assignment to constant variable.
let跟var比较,let限制了作用域,const不能被改变
9. class类
这里东西比较多,后续更新
10. 模块化
这里东西比较多,后续更新