ES6的学习 => 箭头函数

一:箭头函数的格式

  a:一种为只有一条语句,可以省略{}和return。

x => x * x;

    相当于:

function(x) {
    return x * x;
}

  b:一种为多条语句,不可以省略{}和return。

x => {
  if (x > 0) {
    return 1;
  }
  return 2;
}

    相当于:

function(x){
  if (x > 0) {
    return 1;
  }
  return 2;
}

  注意:

    a.当无参数时或有多个参数时,需要用括号()括起来。

(x, y)=> x + y;

    b.当省略{}和return时,返回了一个对象,对象要用括号()括起来。

x=> ({color:"red"});

 

二:箭头函数的this

  a.箭头函数没有自己的 this,其内部的 this 绑定到它的外围作用域。对象内部的箭头函数若有this,则指向对象的外围作用域。

window.color = "red";
//let 声明的全局变量不具有全局属性,即不能用window.访问
let color = "green";
let obj = { color: "blue",
   getColor: () => {
     return this.color;//this指向window
   }
}; let sayColor = () => { return this.color;//this指向window };
obj.getColor();//red
sayColor();//red

   b.箭头函数无法使用 call()或 apply()来改变其运行的作用域。

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

 

 

转载于:https://www.cnblogs.com/yangrenmu/p/6123663.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值