箭头函数能否作为构造函数?
一.什么是箭头函数,和非箭头函数的区别是什么?
箭头函数是ES6中新增加的函数表达类型,其表现形式:
const fun = () => {
}
二. 箭头函数的特点
-
箭头函数表达式没有自己的this,arguments,super或new.target。
-
更简短的函数并且不绑定this
三.我们为什么会使用箭头函数
根据箭头函数的特点,得知箭头函数不绑定this,即内部没有自己的this,说明箭头函数内部的 this 指向是和父this指向是一致的,那么我们在特定的情况下为了方便引用到父函数里的this会去选择使用箭头函数。
this.name = 'ouda'
const fun = () => {
this.name = '123'
}
fun()
console.log(this.name) //123
通过上述代码可以发现我们通过 fun 里的 this.name 改变了 父级的 this.name,原因是 fun 内部的this和父级的this指的是同一个对象。
this.name = 'ouda'
const fun = function () {
this.name = '123'
}
fun()
console.log(this.name) //ouda
不使用箭头函数,打印结果也可想而知。
四. 箭头函数可以做构造函数吗?
我们知道构造函数的 this 指向构造函数创建的对象,并且将会被 return 出去。但是根据箭头函数的特点,箭头函数本身内部不绑定 this ,也没有this指向,这样一来没有办法 创建给参数赋值也没有办法return出去,所以this不能作为构造函数。
其次,非箭头函数内部有两个方法,即 call 和 constructor 方法,但我们调用构造函数的时候,即会调用函数内部的 constructor方法,然而箭头函数内部不存在 constructor方法,所以这也是箭头函数不能作为构造函数的重要原因之一.
尝试验证:
const Person = () => {
this.name = name
}
const p = new Person() // TypeError: Person is not a constructor
综上所述:箭头函数不能作为构造函数。