class Animal{
constructor() {
this.name = 'cat'
}
speak() {
console.log(this.name)
}
eat = () => {
console.log(this.name)
}
}
const n = new Animal()
n.speak()
n.eat()
const a = n.speak
const b = n.eat
b()
a()
n.speak() // cat
n.eat() // cat
小结:
class中的方法如果是普通函数方法,该方法会绑定在构造函数的原型上;但是如果方式是箭头函数方法,该方法会绑定在构造函数上。通过上述方式调用class中的方法,无论是箭头函数方法还是普通函数方法,方法中的this都指向实例对象。
const a = n.speak
const b = n.eat
b() // cat
a()
- 通过引用来调用箭头函数方法,方法中的this依然指向创建的实例对象。
原因:箭头函数中的this,只和定义改箭头函数的位置有关系,即,箭头函数中的this始终是该箭头函数所在作用域中的this。而箭头函数所在的作用域中的this指向foo实例对象。 - 通过引用调用普通函数方法,方法中的this会指向undefined。
原因:因为普通函数中的this是动态绑定的,始终指向函数的执行环境,上面的例子中在全局环境中调用speak方法,但是this确是undefined而不是window。原因在于class声明和class表达式中会默认使用严格模式。