多角度对比 ES5与ES6的区别

ES5与ES6的对比不一样点整理

本文关键词:ES6,javascript,javascript

1.Default Parameters(默认参数)

es6以前,定义默认参数的方法是在一个方法内部定义java

var link = function (height, color, url) {    
    var height = height || 50;
    var color = color || ‘red‘;
    var url = url || ‘https://blog.csdn.net/u011215669‘;
}

es6写法,简单粗暴了不少了node

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

2.Template Literals(模板对象)

es6以前定义模版字符串要这样写(其中first和last 是变量)jquery

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

es6中使用新的语法${ },就简单多啦,注意es6中的模版字符串用得是反引号“(位置如图)es6

这里写图片描述

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

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

es6以前定义多行字符串要这样写编程

var roadPoem = 'Then took the other, as just as fair,'
+ 'And having perhaps the better '
+ '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.';

es6中的模版字符串也能够轻松实现,甚至插入变量也变得很是简单json

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 (解构赋值)

在es5中是这样写的api

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

在nodejs中是这样的数组

var jsonMiddleware = require(‘body-parser‘).jsonMiddleware ;
var body = req.body, // body has username and password
   username = body.username,
   password = body.password;

在es6中就简化了不少promise

var { house, mouse} = $(‘body‘).data(); // we‘ll get house and mouse variables
 var {jsonMiddleware} = require(‘body-parser‘);
 var {username, password} = req.body;

一样适用于数组

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

5.Enhanced Object Literals (加强的对象字面量)

一个典型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()
 }

咱们想让它更有意思,咱们能够用Object.createserviceBase继承原型的方法:

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()
 }

在ES6的对象文本中,既能够直接分配getAccounts: getAccounts,也能够只需用一个getAccounts,此外,咱们在这里经过__proto__(并非经过’proto’)设置属性,以下所示:

var serviceBase = {port: 3000, url: ‘azat.co‘},
  getAccounts = function(){return [1,2,3]};
  var accountService = {
      __proto__: serviceBase,
      getAccounts,
      toString() {
       return JSON.stringify((super.valueOf()));
      },
      getUrl() {return "http://" + this.url + ‘:‘ + this.port},
     [ ‘valueOf_‘ + getAccounts().join(‘_‘) ]: getAccounts()
 };
 console.log(accountService)

ES6对象文本对于旧版的对象文原本说是一个很大的进步。

6.Arrow Functions in(箭头函数)

在ES6中,有了丰富的箭头函数。这些丰富的箭头是使人惊讶的由于它们将使许多操做变成现实,好比,之前咱们使用闭包,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();
 })

一个另外的例子,咱们经过call传递文本给logUpperCase() 函数在ES5中:

var logUpperCase = function() {
    var _this = this;

    this.string = this.string.toUpperCase();
    return function () {
      return console.log(_this.string);
    }
  }

 logUpperCase.call({ string: ‘ES6 rocks‘ })();

而在ES6,咱们并不须要用t_this浪费时间:

var logUpperCase = function() {
   this.string = this.string.toUpperCase();
   return () => console.log(this.string);
 }
 logUpperCase.call({ string: ‘ES6 rocks‘ })();

请注意,只要你愿意,在ES6中=>能够混合和匹配老的函数一块儿使用。当在一行代码中用了箭头函数,它就变成了一个表达式。它将暗地里返回单个语句的结果。若是你超过了一行,将须要明确使用return。

这是用ES5代码建立一个消息数组:

var ids = [‘5632953c4e345e145fdf2df8‘,‘563295464e345e145fdf2df9‘];
 var messages = ids.map(function (value) {
   return "ID is " + value; // explicit return
 });

ES6是这样:

var ids = [‘5632953c4e345e145fdf2df8‘,‘563295464e345e145fdf2df9‘];
 var messages = ids.map(value => `ID is ${value}`); // implicit return

请注意,这里用了字符串模板。在箭头函数中,对于单个参数,括号()是可选的,但当你超过一个参数的时候你就须要他们。在ES5代码有明确的返回功能:

var ids = [‘5632953c4e345e145fdf2df8‘, ‘563295464e345e145fdf2df9‘];
 var messages = ids.map(function (value, index, list) {
   return ‘ID of ‘ + index + ‘ element is ‘ + value + ‘ ‘; // explicit return
 });

在ES6中有更加严谨的版本,参数须要被包含在括号里而且它是隐式的返回:

var ids = [‘5632953c4e345e145fdf2df8‘,‘563295464e345e145fdf2df9‘];
 var messages = ids.map((value, index, list) => `ID of ${index} element is ${value} `); // implicit return

7. Promises

es6中极为强大的promise

Promises 是一个有争议的话题。所以有许多略微不一样的promise 实现语法。Q,bluebird,deferred.js,vow, avow, jquery 一些能够列出名字的。也有人说咱们不须要promises,仅仅使用异步,生成器,回调等就够了。但使人高兴的是,在ES6中有标准的Promise实现。

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

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

在ES6中,咱们能够用promise重写:

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

或者用ES6的箭头函数:

var wait1000 =  new Promise((resolve, reject)=> {
   setTimeout(resolve, 1000);
 }).then(()=> {
   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.Block-Scoped Constructs Let and Const(块做用域和构造let和const)

在ES6代码中,你可能已经看到那熟悉的身影let。在ES6里let并非一个花俏的特性,它是更复杂的。Let是一种新的变量申明方式,它容许你把变量做用域控制在块级里面。咱们用大括号定义代码块,在ES5中,块级做用域起不了任何做用:

function calculateTotalAmount (vip) {
    var amount = 0;
   if (vip) {
      var amount = 1;
    }
    { // more crazy blocks!
      var amount = 100;
      {
      var amount = 1000;
     }
   }  
   return amount;
 }
 console.log(calculateTotalAmount(true));   //输出1000

结果将返回1000,这真是一个bug。在ES6中,咱们用let限制块级做用域。而var是限制函数做用域。

function calculateTotalAmount (vip) {
  var amount = 0; // probably should also be let, but you can mix var and let
  if (vip) {
    let amount = 1; // first amount is still 0
  } 
  { // more crazy blocks!
    let amount = 100; // first amount is still 0
    {
      let amount = 1000; // first amount is still 0
    }
  }  
  return amount;
}

console.log(calculateTotalAmount(true));  //0

9. Classes (类)in ES6

若是你喜欢面向对象编程(OOP),那么你将喜好这个特性。之后写一个类和继承将变得容易。类的建立和使用真是一件使人头疼的事情在过去的ES5中,由于没有一个关键字class (它被保留,可是什么也不能作)。在此之上,大量的继承模型像pseudo classical, classical, functional 更加增长了混乱,JavaScript 之间的宗教战争只会更加火上浇油。用ES5写一个类,有不少种方法,这里就先不说了。如今就来看看如何用ES6写一个类吧。ES6没有用函数, 而是使用原型实现类。咱们建立一个类baseModel ,而且在这个类里定义了一个constructor 和一个 getName()方法:

class baseModel {
    constructor(options, data) { // class constructor,node.js 5.6暂时不支持options = {}, data = []这样传参
      this.name = ‘Base‘;
      this.url = ‘http://azat.co/api‘;
      this.data = data;
      this.options = options;
     }

      getName() { // class method
         console.log(`Class name: ${this.name}`);
     }
 }

注意咱们对options 和data使用了默认参数值。此外方法名也不须要加function关键字,并且冒号(:)也不须要了。另一个大的区别就是你不须要分配属性this。如今设置一个属性的值,只需简单的在构造函数中分配。

AccountModel 从类baseModel 中继承而来:

class AccountModel extends baseModel {
constructor(options, data) {
super({private: true}, [‘32113123123‘, ‘524214691‘]);
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);

结果使人惊讶,输出是:Class name: Account Model Data is 32113123123,524214691

10. Modules (模块)

众所周知,在ES6之前JavaScript并不支持本地的模块。人们想出了AMD,RequireJS,CommonJS以及其它解决方法。如今ES6中能够用模块import 和export 操做了。在ES5中,你能够在 <script></script>中直接写能够运行的代码(简称IIFE),或者一些库像AMD。然而在ES6中,你能够用export导入你的类。下面举个例子,在ES5中,module.js有port变量和getAccounts 方法:

module.exports = {
   port: 3000,
   getAccounts: function() {
     ...
   }
 }

在ES5中,main.js须要依赖require(‘module’) 导入module.js:

var service = require(‘module.js‘);
 console.log(service.port); // 3000

但在ES6中,咱们将用export and import。例如,这是咱们用ES6 写的module.js文件库:

export var port = 3000;
 export function getAccounts(url) {
   ...
 }

若是用ES6来导入到文件main.js中,咱们需用import {name} from ‘my-module’语法,例如:

import {port, getAccounts} from ‘module‘;
 console.log(port); // 3000

或者咱们能够在main.js中把整个模块导入, 并命名为 service:

import * as service from ‘module‘;
 console.log(service.port); // 3000

这里还有许多ES6的其它特性你可能会使用到,排名不分前后:

  1. 全新的Math, Number, String, Array 和 Object 方法

  2. 二进制和八进制数据类型

  3. 默认参数不定参数扩展运算符

  4. Symbols符号

  5. tail调用

  6. Generators (生成器)

  7. New data structures like Map and Set(新的数据构造对像MAP和set)

以上就是我在网上收集整理获得后获得的几点总结,但愿能对你们的学习有所帮助。

参考资源:
* http://es6.ruanyifeng.com/
* https://blog.csdn.net/changsimeng/article/details/62883952
* https://blog.csdn.net/u012860063/article/details/62218564

相关文章
相关标签/搜索