箭头函数和普通函数有什么区别

  • 1.箭头函数相当于匿名函数,是不能作为构造函数的,不能使用new
  • 2.箭头函数不绑定arguments,取而代之用rest参数…解决
  • 3.箭头函数会捕获其所在上下文的this值,作为自己的this值。即箭头函数的作用域会继承自外围的作用域。
  • 4.箭头函数当方法使用的时候没有定义this的绑定
obj = {
  a:10,
  b:()=>{
    console.log(this.a);//undefined
    console.log(this);//window
  },
  c:function(){
    return ()=>{
      console.log(this.a);//10
    }
  }
}
obj.b();
obj.c();

b箭头函数运行时的外围环境是全局作用域,this指向了window 
c内部返回的箭头函数运行在c函数内部,其外围的作用域是外部函数的作用域,外部函数的this值指向调用它的obj,所以输出的值是10

  • 5.使用call()和apply()调用 

通过call()或者apply()调用一个函数时,只是传入参数而已,对this并没有影响。

var obj = {
  a:10,
  b:function(n){
   var f = (v) => v + this.a;
   var c = {a:20};
   return f.call(c,n);
 }
}
console.log(obj.b(1));//11
  • 6.箭头函数没有函数原型
var a = ()=>{
  return 1;
}
function b(){
  return 2;
}
console.log(a.prototype);//undefined;
console.log(b.prototype);//object{...}
  • 7.箭头函数不能当做Generator函数,不能使用yield关键字 
  • 8.箭头函数不能换行
var a = () 
          => 1;//SyntaxError:Unexpected token
 

猜你喜欢

转载自blog.csdn.net/MeetLunay/article/details/83416460