10 个常用的 es6 特性

1. const  and let

    除了函数作用域之外,增加了块级作用域和常量。const 定义的绑定不可以修改,let定义的绑定在{ }不能访问。之前的 var 如果不在函数作用域内,相当于定义了一个全局变量,并且有变量提升(将变量的声明提升至所在函数的最前面)。

2. 数组函数

    新增了一些数组处理函数,可以更加方便的对数组进行操作。

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

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

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

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

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

   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.  函数作为对象方法,可能会被对象方法定义。

    

     

猜你喜欢

转载自www.cnblogs.com/wust-hy/p/9311464.html