首页 > 技术文章 > ES6的十个新特性

Slim-Shady 2016-06-07 14:57 原文

这里只讲 ES6比较突出的特性,因为只能挑出十个,所以其他特性请参考官方文档;

/**
 * Created by zhangsong on 16/5/20.
 */
//    ***********Number One : Parameters************
//                   参数的传递
//ES5:
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 = 'azat.co'){

};

            //Number Two : Template Literals
//                  字面量插入字符串
//ES5

var name = 'your name is' + first + '' + last + '.';
var url =  'http://www.google.com' + id ;

//ES6

var name = `your name is ${first} ${last}.`;
var url = `http://www.google.com ${id}`;

            //Number Three : Multi-line Strings
            //多行字符串
//ES5

var str = 'aaaaaaaaaaaaaaaaa'
    +'bbbbbbbbbbbbbbbbbbbbbb'
    +'cccccccccccccccccccccc';

//ES6

var str = `aaaaaaaaaaaaaaaaaaa
            bbbbbbbbbbbbbbbbbb
            cccccccccccccccccc`;

//              Number Four : Destructuring Assignment
               //读取对象属性或者是数组元素

//ES5:

var a = {
    p1: "this is p1",
    p2: "this is p2"
};
 var p1 = a.p1;
 var p2 = a.p2;

//ES6

var {p1 , p2} = a;

var [p1,p2] = arr.split('\n');

            //Number Five : 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()
};

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

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

            //Number Six: Arrow Functions
            //  箭头方法

//ES5:

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


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


//ES6

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

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


                            //Number Seven : Promises
//ES5

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

//ES6

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

//OR

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

//                       Block-Scoped Constructs Let and Const
//                          块级作用域的变量声明

//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));

//ES6

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

//let 使声明变量不会被提升
//let 严格限制了所声明变量的作用域,在哪声明在哪用
//let 不能重复声明同一个变量
//用 let 可以去掉函数的自执行

//                      Number Nine: Classes
//                           类

//New Concept in js:

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

//                            Number  Ten:  Modules
//                                   模块

//ES5 : Node.js

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

//OR

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

推荐阅读