JavaScript 中 this 指向问题 (普通函数, 箭头函数)

普通函数

  1. 谁调用了函数,那么这个函数中的 this 就指向谁.
    let myFun = function() {
    	console.log(this);
    }
    let obj = {
    	name: "赵云",
    	myFun: function() {
    		console.log(this);
    	}
    }
    
    // 这里的this之所以指向window对象,是因为myFun函数是由window在全局作用域中调用的
    myFun();      // window
    // 这里的this之所以指向obj对象,是因为myFun函数是由obj这个对象调用的
    obj.myFun();  // obj
    
  2. 匿名函数中的this指向:匿名函数的执行具有全局性,则匿名函数中的 this 指向是 window, 而不是调用这个匿名函数的对象.
    let obj = {
    	name: "赵云",
    	myFun: function() {
    		return function() {
    			console.log(this);
    		}
    	}
    }
    obj.myFun()();    // window
    

    上面的代码中,myFun 方法是由 obj 对象调用的,但是 obj.myFun() 返回的是一个匿名函数,而匿名函数中的 this 指向 window,所以打印 window;
    如果上面的代码中使 this 指向调用这个方法的对象,可以提前把 this 传值给另一个变量(_this);

    let obj = {
    	name: "赵云",
    	myFun: function() {
    		let _this = this;
    		return function() {
    			console.log(_this);
    		}
    	}
    }
    obj.myFun()();    // obj
    

箭头函数

  1. 箭头函数中的 this 在定义函数时就已经被确认了,而不是在函数调用的时候确认的;
  2. 箭头函数中的 this 指向父级作用域的执行上下文;(解释:JavaScript 中除了全局作用域,其他作用域都是由函数创建出来的,如果想确认 this 指向,则找到离箭头函数最近的function,与这个function平级的执行上下文中的 this 就是箭头函数中的 this);
  3. 箭头函数无法使用 call, bind, apply改变 this 指向,是因为 this 在函数定义的时候已经被确认;

举例一:距离箭头函数最近的函数是 myFun,与这个函数最近的上下文中 this 指向 obj, 所以箭头函数中 this 的指向为 obj

let obj = {
    name: "赵云",
    // 这里的this指向就是箭头函数中this的指向
    myFun: function() {
        return () => {
            console.log(this);
        }
    }
}
obj.myFun()();    // obj

举例二: 这段代码中存在两个箭头函数,this 找不到离它最近的函数作用域,所以一直往上找指向 window;

let obj = {
    name: "赵云",
    myFun: () => {
        return () => {
            console.log(this);
        }
    }
}
obj.myFun()();    // window
posted @ 2022-03-02 17:19  太轻描淡写了  阅读(191)  评论(0编辑  收藏  举报