说说 ECMAScript 6 箭头函数

查看更多文章: https://alili.tech

在es6中可以使用箭头函数(Arrow Functions)

var foo = (a) => a;
foo("hello word"); //hello word

等价于

var foo = function(a){
  return a
}
foo("hello word"); //hello word

以上函数只有一个参数,还可以写成连括号都不需要:

var foo = a => a;
foo("hello word"); //hello word

如果函数没有参数,就必须要加上括号了:

var foo = () => {
  alert("hello word");
};

作为事件句柄

document.addEventListener('click', event => {
    console.log(event)
})

回调

$("button").hover(
  ()=>{
  //鼠标移入
  console.log("鼠标移入");
},
  ()=>{
  //鼠标移出
  console.log("鼠标移出");
})

使用箭头函数之后,this将会继承外围作用域的this,举个例子

var oImage = new Image()
var oImage2 = new Image()
document.getElementById("button").onclick=() => {

  //没有外围作用域,所以this是undefined
  console.log(this); // 这里的this是undefined

  oImage.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";
  oImage2.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";

  //这里使用了箭头函数,this将会继承外围作用域的this,
  //可是外围的this也是undefined,所以这里还是undefined
  oImage.onload=() => {
    console.log(this)// 这里的this是undefined
  }

  //这里没有用箭头函数
  oImage2.onload=function(){
    console.log(this)// 这里的this 将会是image对象
  }

}

换一种写法,最外层使用传统的function写法

var oImage = new Image()
var oImage2 = new Image()
document.getElementById("button").onclick=function(){

  //这里没有使用箭头函数,所以this是button
  console.log(this); // 这里的this是button

  oImage.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";
  oImage2.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";

  //这里使用了箭头函数,this将会继承外围作用域的this
  oImage.onload=() => {
    console.log(this)// 这里的this还是button
  }

  //这里没有用箭头函数
  oImage2.onload=function(){
    console.log(this)// 这里的this 将会是image对象
  }

}

公众号“ Alili丶前端大爆炸”,关注后提供海量学习资料

图 1

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值