我们都知道,箭头函数的this
的指向在函数声明时即已经确定了,所以不能够使用箭头函数来声明构造函数。
let Person;
Person = (name, age) => {
this.name = name;
this.age = age;
}
new Person('frx', 20);
运行结果:
有没有思考过为什么会报错呢?真的只是this
的指向的问题吗?
实际上,js里面每个非箭头函数都有两个内部方法,一个是
[[call]]
,另一个是[[construct]]
,在不是用new
进行调用函数时,函数会调用内部的[[call]]
方法,而使用new
调用时,函数会调用内部的[[construct]]
方法。
而对于箭头函数来说,箭头函数是没有[[construct]]
的内部方法的,这个才是箭头函数不能作为构造函数的真正原因。
另外,我们还要注意的是,在使用class
关键字声明的类中声明的方法同样没有[[construct]]
。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName() {
console.log(this.name);
}
}
var person = new Person();
new person.sayName();
/*
*Uncaught TypeError: person.sayName is not a constructor
*/
好了,你get到我说的内容了吗?希望能帮助到你哦o( ̄▽ ̄)ブ!