一、箭头函数的 this 指向哪里?
箭头函数不同于传统 JavaScript 中的函数,箭头函数并没有属于⾃⼰的 this,它所谓的 this 是捕获其所在上下⽂的 this 值,作为⾃⼰的 this 值,并且由于没有属于⾃⼰的 this,所以是不会被 new调⽤的,这个所谓的 this 也不会被改变。
可以⽤Babel 理解⼀下箭头函数:
//ES6
const obj = {
getArrow(){
return () => {
consloe.log(this === obj);
};
}
}
转化后
//ES5,由Babel转译
var obj = {
getArrow: function getArrow(){
var _this = this;
return function () {
consloe.log(_this === obj);
}
}
}
总结
以上就是今天要讲的内容,本文仅仅介绍了箭头函数的 this 指向哪里。