• Home
  • Archives
  • About
  • Github
  • zh


ECMAScript 6 之箭头函数

在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对象
  }

}

微信公众号

本文链接:

https://alili.tech/archive/918f85ad/

# 最新文章