差异
- 普通函数:
this
的指向在函数被调用时确定,取决于函数的调用方式。
- 全局作用域中:在非严格模式下,普通函数内部的
this
指向全局对象(浏览器中是 window
);在严格模式下,this
是 undefined
。
- 作为对象方法调用:
this
指向调用该方法的对象。
- 通过
call
、apply
、bind
调用:this
指向传入的第一个参数。
- 箭头函数:
this
的指向在定义时确定,取决于外层(函数或全局)作用域的 this
。它没有自己的 this
绑定,会捕获其所在上下文的 this
值,作为自己的 this
值。
实际代码场景示例
- 普通函数示例
function NormalFunction() {
console.log(this);
}
// 非严格模式下,在全局作用域调用
NormalFunction(); // 在浏览器中输出 window 对象
const obj = {
name: 'test',
normalFunc: function() {
console.log(this.name);
}
};
obj.normalFunc(); // 输出 'test',this 指向 obj
function anotherFunc() {
console.log(this.name);
}
const newObj = { name: 'newTest' };
anotherFunc.call(newObj); // 输出 'newTest',通过 call 改变 this 指向 newObj
- 箭头函数示例
const obj2 = {
name: 'arrowTest',
arrowFunc: () => {
console.log(this.name);
}
};
obj2.arrowFunc();
// 这里的 this 指向全局作用域(浏览器中是 window),通常 window 上没有 name 属性,所以输出 undefined
function outer() {
this.name = 'outerTest';
return () => {
console.log(this.name);
};
}
const arrow = outer.call({name: 'callTest'});
arrow();
// 这里箭头函数的 this 指向 outer 函数调用时的 this,即 {name: 'callTest'},输出 'callTest'