javascript 中 this 在方法调用中指向调用该方法的对象。具体做法是确保方法作为对象的属性被访问并调用,此时 this 自动绑定到该对象;若通过引用变量调用,this 仍指向拥有该方法的对象,而非引用变量本身。

直接调用函数时 this 指向谁
直接调用函数时 this 指向全局对象(浏览器中为 window,严格模式下为 undefined)。这是因为直接调用没有明确的调用者对象,JavaScript 引擎无法确定上下文,因此回退到默认绑定规则。

function directCall() {
console.log(this === window); // true (非严格模式)
}
directCall();
'use strict';
function strictDirectCall() {
console.log(this); // undefined
}
strictDirectCall();
预期结果:非严格模式下输出 true,严格模式下输出 undefined。这验证了直接调用时 this 的绑定行为取决于是否启用严格模式。
使用 call 或 apply 显式绑定 this 指向谁
使用 call 或 apply 显式绑定 this 指向传入的第一个参数对象。call 和 apply 的区别在于参数传递方式:call 接受参数列表,apply 接受参数数组。两者都强制改变 this 的指向,绕过默认的调用者绑定规则。

const obj = { name: 'Alice' };
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
greet.call(obj, 'Hello'); // Hello, Alice
greet.apply(obj, ['Hi']); // Hi, Alice
预期结果:两次调用均输出包含 obj.name 的结果,证明 call 和 apply 成功将 this 绑定到 obj 对象。这展示了显式绑定的可控性,适用于需要动态改变上下文的场景。
箭头函数中的 this 指向谁
箭头函数中的 this 指向定义时所在作用域的 this,而非调用时的对象。这是因为箭头函数没有自己的 this 绑定,它继承外层函数的 this 值。这种特性使得箭头函数在回调场景中特别有用,避免了传统函数中 this 丢失的问题。
const obj = {
name: 'Bob',
regularMethod: function() {
console.log(this.name); // Bob
},
arrowMethod: () => {
console.log(this.name); // undefined (假设在全局作用域定义)
}
};
obj.regularMethod();
obj.arrowMethod();
预期结果:regularMethod 输出 Bob,arrowMethod 输出 undefined。这证实了箭头函数不绑定 this,而是捕获外层作用域的 this 值。在实际开发中,应避免在对象方法中使用箭头函数,除非明确需要继承外层 this。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











