勉叠教育
您的当前位置:首页有关JavaScript中this指向问题的深度解析

有关JavaScript中this指向问题的深度解析

来源:勉叠教育


  这里已经清楚了说明了,箭头函数没有自己的 this 绑定。箭头函数中使用的 this,其实是直接包含它的那个函数或函数表达式中的 this。比如

const obj = {
 test() {
 const arrow = () => {
 // 这里的 this 是 test() 中的 this,
 // 由 test() 的调用方式决定
 console.log(this === obj);
 };
 arrow();
 },

 getArrow() {
 return () => {
 // 这里的 this 是 getArrow() 中的 this,
 // 由 getArrow() 的调用方式决定
 console.log(this === obj);
 };
 }
};

obj.test(); // true

const arrow = obj.getArrow();
arrow(); // true

  示例中的两个 this 都是由箭头函数的直接外层函数(方法)决定的,而方法函数中的 this 是由其调用方式决定的。上例的调用方式都是方法调用,所以 this 都指向方法调用的对象,即 obj。

  箭头函数让大家在使用闭包的时候不需要太纠结 this,不需要通过像 _this 这样的局部变量来临时引用 this 给闭包函数使用。来看一段 Babel 对箭头函数的转译可能能加深理解:

// ES6
const obj = {
 getArrow() {
 return () => {
 console.log(this === obj);
 };
 }
}
// ES5,由 Babel 转译
var obj = {
 getArrow: function getArrow() {
 var _this = this;
 return function () {
 console.log(_this === obj);
 };
 }
};

  另外需要注意的是,箭头函数不能用 new 调用,不能 bind() 到某个对象(虽然 bind() 方法调用没问题,但是不会产生预期效果)。不管在什么情况下使用箭头函数,它本身是没有绑定 this 的,它用的是直接外层函数(即包含它的最近的一层函数或函数表达式)绑定的 this。

显示全文