箭头函数的特点/作用

一、箭头函数的特点

箭头函数是匿名函数

1. 箭头函数使表达更加简洁,隐式返回值

const isEven = n => n % 2 === 0;
const square = n => n * n;

箭头函数的一个用处是简化回调函数,如下:

// 正常函数写法
[1,2,3].map(function (x) {
  return x * x;
});

// 箭头函数写法
[1,2,3].map(x => x * x); //[1,4,9]

 

 

2. 没有自己的this


箭头函数中的this实际是外层函数的this(箭头函数的this对象是定义时所在的对象,而不是使用时的对象)

箭头函数最大的一个好处就是它的 this指向定义时所在环境的 this ,而非使用时环境的 this,比如在SetTimeeout 函数的回调函数中,如果使用箭头函数,那么THIS还是指向调用 SetTimeeout 的对象里的this 。

function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => this.s1++, 1000);

  // 普通函数
  setInterval(function () {
    this.s2++;
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100); // s1: 3
setTimeout(() => console.log('s2: ', timer.s2), 3100); // s2: 0

由于在vue中自动绑定 this 上下文到实例中,因此不能使用箭头函数来定义一个周期方法。箭头函数的this永远指向上下文的this,不能用call()、apply()、bind()这些方法去改变this的指向


3. 箭头函数不能当作构造函数使用、不能使用new

let foo=()=>{
 
}
var newFoo=new foo()//foo is not a construcotr


4. 不能使用argumetns,取而代之用rest参数...解决

不存在arguments对象
该对象在函数体内不存在。如果要用,可以用 rest 参数代替。
rest形式为(…变量名)可以获取函数的多余参数,并且获取到的是真正的数组对象
arguments只是一个类数组对象,除了length属性和可以使用arguments[0]获取元素之外没有数组的其他特性,可以使用[…arguments]或者Array.prototype.slice.call(arguments,0)、Array.prototype.concat.call(arguments,0)转为数组

let C = (...c) => {
  console.log(c);
}
C(1,2,3,3)

5. 箭头函数没有原型对象

没有prototype属性

var foo = () => {  
    return 1  
}  
function bar(){  
    return 2;  
}  
console.log(foo.prototype)  //undefined  
console.log(bar.prototype)  // {constructor:f}

 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值