ES6 新特性
概述 :主要的十个新特性
- Default Parameters(默认参数) in ES6
- Template Literals (模板文本)in ES6
- Multi-line Strings (多行字符串)in ES6
- Destructuring Assignment (解构赋值)in ES6
- Enhanced Object Literals (增强的对象文本)in ES6
- Arrow Functions (箭头函数)in ES6
- Promises in ES6
- Block-Scoped Constructs Let and Const(块作用域构造Let and Const)
- Classes(类) in ES6
- Modules(模块) in ES6
1.默认参数
2.模板文本
- var name = `Your name is ${first} ${last}. `;
- var url = `http://localhost:3000/api/messages/${id}`;
3.多行字符串
- 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,`;
4.解构赋值
[javascript] view plain copy
- var { house, mouse} = $('body').data(); // we'll get house and mouse variables
- var {jsonMiddleware} = require('body-parser');
- var {username, password} = req.body;
这个同样也适用于数组,非常赞的用法:
[javascript] view plain copy
- var [col1, col2] = $('.column'),
- [line1, line2, line3, , line5] = file.split('n');
5.增强对象文本 (略 ,有点晦涩)
6.箭头函数 (非常nice的特性)
以前我们使用闭包,this总是预期之外地产生改变,而箭头函数的迷人之处在于,现在你的this可以按照你的预期使用了,身处箭头函数里面,this还是原来的this。
有了箭头函数在ES6中, 我们就不必用that = this或 self = this 或 _this = this 或.bind(this)。例如,下面的代码用ES5就不是很优雅:
- var _this = this;
- $('.btn').click(function(event){
- _this.sendData();
- })
在ES6中就不需要用 _this = this:
- $('.btn').click((event) =>{
- this.sendData();
- })