es6的箭头函数

1.使用语法 : 参数 => 函数语句;

分为以下几种形式 : 

(1) ()=>语句

  (  )=> statement 这是一种简写方法省略了花括号和return 相当于 ()=>{return statement;}

   这和 匿名函数 function(){return statement;}等同

  零个参数用()表示;

(2)    (  ) =>{多行语句}

  多行语句就不能省略花括号了,没有写return则返回 undefined;

(3)    x =>{statement return y}   x=>statement 当只有一个参数时可以省略小括号;

   这和 匿名函数 function(x){ statement return y;}等同

(4)     (x,y,z) = >{statement return z}   (x,y,z)=>statement  多个参数必须有小括号;

(5)    ()=>({ob:"this is object"}) 

  使用简写方式当返回值是一个对象时需要加上小括号;这是因为花括号在js中表示可执行代码段也表示对象集合所以为了避免错误必须有小括号;

  使用()=>{return {object :" obj "}} 则不必添加小括号(添加了也不会有错);

2.箭头函数的特性

(1) 箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作

  new (() => {}) //此处会报错

(2)它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时,并且call和aply无法改变this的指向;

window.color = "red";
let color = "green";
let obj = {
  color: "blue"
};
let sayColor = () => {
  return this.color;
};
sayColor.apply(obj);//red

 

原文地址:https://www.cnblogs.com/lizhiwei8/p/7677095.html