10 个经常使用的 es6 特性

1. const  and letes6

    除了函数做用域以外,增长了块级做用域和常量。const 定义的绑定不能够修改,let定义的绑定在{ }不能访问。以前的 var 若是不在函数做用域内,至关于定义了一个全局变量,而且有变量提高(将变量的声明提高至所在函数的最前面)。数组

 

2. 数组函数promise

    新增了一些数组处理函数,能够更加方便的对数组进行操做。app

    let a = Array.foreach( functionA )  functionA 会对函数的每一元素进行操做,a = undefined。函数

    let b = Array.map( functionA ), 与foreach 的不一样的是map 会返回一个新的数组。this

    let c = Array.filter( functionA ), 与map不一样的是,filter 返回的数组Array 的一个子集。spa

   let d = Array.find( functuonB ) , 找到符合条件的值立马返回。rest

   let e = Array.every( checkFunc) , check 每个 element , all ok 则 返回 true, else return false.code

   let g = Array.some( checkFunc), if any element passes the check, retrun ture, else return false.对象

  let  h = Array.reduce(function, initArgument), 提供操做和初始值函数,最终返回一个值。

 

3. 箭头函数

   ()=> {}    -- 参数函数体。当参数只有一个,函数体只有一行时能够写成 a => a*a的形式,省略()和{},其中a*a为函数的返回值。

    与以前函数不一样,箭头函数不会绑定this,arguments,super等局部变量,全部涉及到它们的引用都会沿着向上查找的方式在外层查找。

    因此箭头函数不能用 apply,call,bind来绑定函数内部的this。

    按词法做用域,Lexical Scoping just means that it uses  this from the code that contains the Arrow Function.。即从包含箭头函数的上下文做用域里去查找this。

    而用 function 定义的函数,则this其实是在函数被调用时发生绑定,它指向什么彻底取决于函数在哪里被调用。

 

4.类

  es6 中的类实际上原型继承的语法糖,constructor就是构造函数,建立一个对象,而在类中添加函数,就是在对象的原型链上添加方法。

 

5. 加强的对象字面量

    <1> 能够引用上下文做用域中的变量

    <2> 直接定义方法

    <3> 定义动态属性

const color = 'red'
const point = { x: 5, y: 10, color, toString() { return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color }, [ 'prop_' + 42 ]: 42 }

 

6.模板字符串

   直接在字符串中使用变量,避免使用 + 来链接变量。

function hello(firstName, lastName) { return `Good morning ${firstName} ${lastName}! How are you?` }

 

7.默认函数参数

   默认指定函数参数的默认值,当传入参数的时候会覆盖默认值。

function sort(arr = [], direction = 'ascending') { console.log('I\'m going to sort the array', arr, direction) }

 

8.解构和剩余操做符

// 解构
var array = ['red', 'blue', 'green'] var copyOfArray = [...array] //rest opoerator
function printColors(first, second, third, ...others) { console.log('Top three colors are ' + first + ', ' + second + ' and ' + third + '. Others are: ' + others) }

 

9. 从数组中提取须要的值,传入变量,也包括对象。

 let [first, , third] = [1,2,3];
let obj = {a:100,b:200};
let {a}= obj;

 

10. promise

     promise.then().catch();

 

总结

    1.构造函数可能会被类修饰符替代。

    2. 函数做为子程序,可能会被箭头函数替代。

   3.  函数做为对象方法,可能会被对象方法定义。

相关文章
相关标签/搜索