this的指向由函数调用方式决定:全局环境中指向全局对象;对象方法中指向调用者;构造函数中指向新实例;事件处理中指向绑定元素;箭头函数继承外层作用域;call、apply、bind可显式绑定this。

在 JavaScript 中,this 的指向不是由函数定义决定的,而是由函数调用的方式决定的。理解 this 的指向是掌握 JS 面向对象和函数执行机制的关键。以下是 this 常见的使用场景及其指向规则。
在全局作用域中,this 指向全局对象:
注意:严格模式下,在全局函数中调用 this 仍指向全局对象,但直接调用函数时 this 为 undefined(如 IIFE 严格模式)。当函数作为对象的方法被调用时,this 指向该对象。
const person = {
name: 'Alice',
sayName() {
return this.name;
}
};
person.sayName(); // 'Alice' —— this 指向 person
const fn = person.sayName; fn(); // undefined(非严格模式下为 window.name)
使用 new 调用函数时,this 指向新创建的实例对象。
function Person(name) {
this.name = name; // this 指向 new 出来的实例
}
const p = new Person('Bob');
p.name; // 'Bob'
DOM 事件处理中,this 通常指向绑定事件的元素。
button.addEventListener('click', function() {
console.log(this); // this 指向 button 元素
});
箭头函数没有自己的 this,它的 this 继承自外层普通函数或全局作用域。
const obj = {
name: 'Tom',
greet: () => {
console.log(this.name); // this 指向外层,通常是 window 或 module
},
delayGreet() {
setTimeout(() => {
console.log(this.name); // 'Tom',箭头函数捕获 delayGreet 的 this
}, 100);
}
};
可以通过方法手动指定 this 指向。
function introduce() {
console.log(`I am ${this.name}`);
}
const user = { name: 'John' };
introduce.call(user); // 'I am John'
基本上就这些常见场景。掌握 this 的核心是看函数如何被调用,而不是定义位置。实际开发中常结合 bind、箭头函数来稳定上下文,避免意外指向。不复杂但容易忽略细节。
以上就是js中this的使用场景的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号