Open zlx362211854 opened 4 years ago
function A() {
this.a = () => {}
this.c = () => {}
this.d = function() {}
}
A.prototype.b = function() {}
首先,constructor内部的属性c,d在作用在其函数本身上,其次箭头函数a由于指向外部域,所以也指向构造方法,直接定义的函数b由于是普通函数,会绑定在类的prototype上。
JavaScript 可以通过原型来继承父级的属性,所以可以用原型来改写类:
function A() {
this.c = () => {console.log(this)}
this.d = function() {console.log(this)}
/**
* A.prototype.a = () => {console.log(this)}
* 如果把箭头函数挂到原型上,那么 this 会指向全局,为了绑定 this,所以将 a 方法写到函数内部
*
*/
this.a = () => {console.log(this)}
}
A.prototype.b = function() {console.log(this)}```
将下面类写法改成函数写法