发现以下两种对象中的箭头函数,this指向不同,请问大神们该如何解释呢?
代码一
const person = {
show: () => {
console.log(this); // why window
}
}
person.show();
代码二
class Person {
show = () => {
console.log(this); //why person
}
}
const person = new Person();
person.show()
已知悉,箭头函数中的this是指向上一层作用域中的this,如果没有,会一直往上找,直到顶层,在浏览器中自然是this。所以第一种好理解,应该是对象变量中的{}不是具备作用域范围;问题在于第二种怎么解释呢。
这样是不是就好理解了