-
Notifications
You must be signed in to change notification settings - Fork 17
Open
Labels
Description
先放结论:
箭头函数体内的this对象,就是定义该函数时所在的作用域指向的对象,而不是使用时所在的作用域指向的对象。
大白话就是往外找父函数,箭头函数的this = 父函数中的this,没有父函数,那么this就是window。
看一段代码
const name = 'window';
const a = {
name: 'a',
sayHello: () => {
console.log(this.name)
},
that: this
}
a.sayHello(); // 输出a ? 错啦,其实输出的是w, 通过a.that就可以验证this到底是谁
这里的箭头函数,也就是sayHello,所在的作用域其实是最外层的js环境,因为没有其他函数包裹;然后最外层的js环境指向的对象是winodw对象,所以这里的this指向的是window对象。
再看一段代码
const name = 'window';
const a = {
name: 'a',
sayHello: function(){
const s = () => console.log(this.name)
return s//返回箭头函数s
}
}
const sayHello = a.sayHello();
sayHello(); // 输出a
箭头函数s 所在的作用域是sayHello,因为sayHello是一个函数,sayHello里的this就是对象a,所以s箭头函数的this就是a。
来看下class
class Person {
constructor(name,age){
this.name = name
this.age = age
}
study = () => {
//study方法放在了哪里?——类的原型对象上,供实例使用
//通过Person实例调用study时,study中的this就是Person实例
console.log(this);
}
}
const p1 = new Person('tom',18)
p1.study() //通过实例调用study方法
const x = p1.study
x()
箭头函数study,所在作用域是class Person,this始终指向的是实例。