一、普通函数体中的this指向
隶属于执行上下文,
this
指向取决于调用方式
调用方式 | 示例 | 函数体中的this指向 |
---|---|---|
通过new调用 | new func() | 新对象 |
通过对象调用 | obj.func() | 调用对象(obj) |
直接调用 | func() | 全局对象 |
call、apply、bind | func.call(thisArg, …) | thisArg |
二、箭头函数体中的this指向
隶属于词法作用域,
this
指向取决于定义箭头函数的作用域中的this。换而言之,箭头函数不存在this的概念。
function A(){
this.bObj = new B();
(()=>console.log("定义在a函数作用域环境中的箭头函数this指向",this))()
}
function B(){
this.fn = function (func){
func();
(()=>console.log("定义在b函数作用域环境中的箭头函数this指向",this))();
}
}
const aObj = new A();
aObj.bObj.fn(()=>console.log("定义在全局作用域环境中的箭头函数this指向",this));
aObj.bObj.fn(()=>{
console.log("定义在全局作用域环境中的箭头函数this指向",this);
(()=>console.log("定义在箭头函数作用域环境中的箭头函数this指向",this))();
});
输出结果:
`