箭头函数--入门(学习笔记)

箭头函数(Arrow Functions)

一、更简洁的写法

1.原来的写法

function method(params){
  return params*2;
}

2.箭头函数

(params)  => {params*2;} 

一行搞定。

a.若只有一个参数,括号可省略

params  => {params*2;} 

b.若只有一个表达式,花括号可省略

params => params*2;

二、不会改变this指向

例:实现a++

var Method = function(){
  this.a = 0;
  this.timer = setInterval(function(){
    this.a++;
    console.log(this.a);
  },1000);
}
var method = new Method();

输出:

NaN
NaN
NaN
...

因为在setInterval函数中,this,指向windows,windows中的a未定义,所以无法输出想要的值。

修改为箭头函数,则可实现a++;

var Method = function(){
  this.a = 0;
  this.timer = setInterval(() => {
    this.a++;
    console.log(this.a);
  })
}
var method = new Method();

输出:

1
2
3
...

猜你喜欢

转载自www.cnblogs.com/leepy/p/12602278.html