箭头函数

198 阅读1分钟

一、this对象

箭头函数体内的this对象,是定义时所在的对象,而不是使用时所在的对象。箭头函数本身没有this,其绑定的this是离他最近的非箭头函数的this。


举个栗子:

var point = 35;
let arrow = {
    point: 10,
    myfunc: function(){
       console.log(this.point)
    },
    myarrow: () => {
      //console.log(this)
      console.log(this.point)  
    }    
}

arrow.myfunc()  //  10   ==>相当于 arrow.myfunc.call(arrow)
arrow.myarrow() //  35

arrow.myfunc.call({point:50})   // 50
arrow.myarrow.call({point:50})  // 35

普通函数体内的this是其被调用时所在的对象,即谁调用它,this就是谁。

箭头函数myarrow外部没有非箭头函数,此时this指向Window,当然,因为箭头函数没有this,所以不能call\apply\bind。


二、箭头函数不能当构造函数

箭头函数没有[[Constructor]]方法

举个栗子:

 var Arrow = () => {}
 var a = new Arrow()
 报错信息:
 18:10:02.239 VM1108:1 Uncaught TypeError: Arrow is not a constructor
    at <anonymous>:1:9

我们知道普通函数当new 一个实例对象时,会将this绑定到这个实例对象上,但是箭头函数不存在[[Constructor]]方法,也就不存在this绑定到实例对象上。


三、箭头函数不存在arguments

不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。

举个栗子:

function somefunc(){
   console.log(arguments[0])
}

var otherfunc = () => {
   console.log(arguments[0])
}

somefunc(1)  // 1
otherfunc(2)  //报错  Uncaught ReferenceError: arguments is not defined

function another() {
  return () => console.log(arguments[0])
}
another(2)()  // 2 

虽然箭头函数没有自己的arguments,但是它可以获取外部函数的arguments。

四、箭头函数没有原型、没有super、不可以使用yield命令

箭头函数不能当作构造函数,所以它也不存在原型,没有原型,所以也不能通过super去访问原型的属性。