前端开发不得不知的ES6十大新特性

3,777 阅读3分钟

es6排名前十的最佳特性列表

  1. 默认参数 in es6
  2. 模板文本 in es6
  3. 多行字符串 in es6
  4. 解构赋值 in es6
  5. 增强的对象文本 in es6
  6. 箭头函数 in es6
  7. Promise in es6
  8. 块作用域构造Let and Const
  9. Classes 类 in es6
  10. Modules 模块 in es6

1.Default Parameters(默认参数) in ES6

还记得我们以前(ES5)不得不通过下面方式来定义默认参数:

var link = function (height, color, url) {
  var height = height || 50;
  var color = color || 'red';
  var url = url || 'http://azat.co';
    ...
}

一切工作都是正常的,直到参数值是0后,就有问题了,因为在JavaScript中,0表示false 但在ES6,我们可以直接把默认值放在函数申明里:

var link = function(height = 50, color = 'red', url = 'http://azat.co') {
  ...
}

2.Template Literals(模板对象) in ES6

在其它语言中,使用模板和插入值是在字符串里面输出变量的一种方式。 因此,在ES5,我们可以这样组合一个字符串:

var name = 'Your name is ' + first + ' ' + last + '.';
var url = 'http://localhost:3000/api/messages/' + id;

幸运的是,在ES6中,我们可以使用新的语法$ {NAME},并把它放在反引号里:

var name = `Your name is ${first} ${last}. `;
var url = `http://localhost:3000/api/messages/${id}`;

3.Multi-line Strings (多行字符串)in ES6

ES6的多行字符串是一个非常实用的功能。 在ES5中,我们不得不使用以下方法来表示多行字符串:

var roadPoem = 'Then took the other, as just as fair,nt'
  + 'And having perhaps the better claimnt'
  + 'Because it was grassy and wanted wear,nt'
  + 'Though as for that the passing therent'
  + 'Had worn them really about the same,nt';
    
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.Destructuring Assignment (解构赋值)in ES6

解构可能是一个比较难以掌握的概念。先从一个简单的赋值讲起,其中house 和 mouse是key,同时house 和mouse也是一个变量,在ES5中是这样:

// data has properties house and mouse
var data = $('body').data();
var house = data.house,
var mouse = data.mouse;

在ES6,我们可以使用这些语句代替上面的ES5代码:

// we'll get house and mouse variables
var { house, mouse } = $('body').data();

这个同样也适用于数组,非常赞的用法:

var [col1, col2]  = $('.column');
var [line1, line2, line3, , line5] = file.split('n');

5. 增强的对象字面量

对象字面量已得到了增强。现在我们可以更容易地:

  • 定义具有相同名称的变量赋值字段
  • 定义函数
  • 定义动态属性
const color = 'red'
const point = {
  x: 5,
  y: 10,
  color,
  toString() {
    return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color
  },
  [ 'prop_' + 42 ]: 42
}

console.log('The point is ' + point)
console.log('The dynamic property is ' + point.prop_42)
The point is X=5, Y=10, color=red 
The dynamic property is 42 

6.Arrow Functions in(箭头函数) ES6

例如,下面的代码用ES5就不是很优雅:

var _this = this;
$('.btn').click(function(event) {
  _this.sendData();
});

在ES6中就不需要用 _this = this:

$('.btn').click((event) => {
  this.sendData();
});

7. Promises in ES6

下面是一个简单的用setTimeout()实现的异步延迟加载函数:

setTimeout(function() {
  console.log('Yay!');
}, 1000);

在ES6中,我们可以用promise重写:

var wait1000 =  new Promise(function(resolve, reject) {
  setTimeout(resolve, 1000);
}).then(function() {
  console.log('Yay!');
});

到目前为止,代码的行数从三行增加到五行,并没有任何明显的好处。确实,如果我们有更多的嵌套逻辑在setTimeout()回调函数中,我们将发现更多好处:

setTimeout(function(){
  console.log('Yay!');
  setTimeout(function(){
    console.log('Wheeyee!');
  }, 1000);
}, 1000);

在ES6中我们可以用promises重写:

var wait1000 =  ()=> new Promise((resolve, reject)=> {
  setTimeout(resolve, 1000);
});
wait1000()
  .then(function() {
    console.log('Yay!')
    return wait1000()
  })
  .then(function() {
    console.log('Wheeyee!')
  });

8.(块作用域和构造let和const)

const用于定义常量。 let用于定义变量。但是JavaScript中不是已经有变量了吗? 是的,这很正确,但用var声明的变量具有函数作用域,并会被提升到顶部。 这意味着在声明之前就可以使用这个变量。 let变量和常量具有块作用域(用{}包围),在声明之前不能被使用。

9. Classes (类)in ES6

用ES5写一个类,有很多种方法,这里就先不说了。现在就来看看如何用ES6写一个类吧。ES6没有用函数, 而是使用原型实现类。我们创建一个类baseModel ,并且在这个类里定义了一个constructor 和一个 getName()方法:

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}`);  
    }  
}  

10. Modules (模块)in ES6

在ES6 Module出现之前,模块化一直是前端开发者讨论的重点,面对日益增长的需求和代码,需要一种方案来将臃肿的代码拆分成一个个小模块,从而推出了AMD,CMD和CommonJs这3种模块化方案,前者用在浏览器端,后面2种用在服务端,直到ES6 Module出现 ES6 Module使用import关键字导入模块,export关键字导出模块,它还有以下特点:

  • ES6 Module是静态的,也就是说它是在编译阶段运行、编译阶段就能确定模块的依赖关系,以及输入和输出的变量
  • ES6 Module支持使用export {<变量>}导出具名的接口,或者export default导出匿名的接口