js中this的使用场景

29次阅读

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

js中this的使用场景

javaScript 中,this 的指向不是由函数定义决定的,而是由函数调用的方式决定的。理解 this 的指向是掌握 js 面向对象和函数执行机制的关键。以下是 this 常见的使用场景及其指向规则。

1. 全局环境中的 this

在全局作用域中,this 指向全局对象:

注意:严格模式下,在全局函数中调用 this 仍指向全局对象,但直接调用函数时 this 为 undefined(如 IIFE 严格模式)。

2. 对象方法中的 this

当函数作为对象的方法被调用时,this 指向该对象。

const person = {   name: 'Alice',   sayName() {     return this.name;   } }; person.sayName(); // 'Alice' —— this 指向 person

如果方法被赋值给变量再调用,this 会丢失指向。

const fn = person.sayName; fn(); // undefined(非严格模式下为 window.name)

3. 构造函数中的 this

使用 new 调用函数时,this 指向新创建的实例对象。

function Person(name) {   this.name = name; // this 指向 new 出来的实例 } const p = new Person('Bob'); p.name; // 'Bob'

构造函数中 return 非对象类型时,this 仍返回实例;若 return 对象,则返回该对象。

4. 事件处理函数中的 this

dom 事件处理中,this 通常指向绑定事件的元素。

js中this的使用场景

MCP市场

中文MCP工具聚合与分发平台

js中this的使用场景 77

查看详情 js中this的使用场景

button.addEventListener('click', function() {   console.log(this); // this 指向 button 元素 });

使用箭头函数时,this 不绑定,会继承外层作用域。

5. 箭头函数中的 this

箭头函数没有自己的 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 上下文,避免 bind 或缓存 this。

6. 显式绑定:call、apply、bind

可以通过方法手动指定 this 指向。

  • call/apply:立即调用,传入 this 值和参数
  • bind:返回新函数,this 固定为传入值
function introduce() {   console.log(`I am ${this.name}`); } const user = { name: 'John' }; introduce.call(user); // 'I am John'

基本上就这些常见场景。掌握 this 的核心是看函数如何被调用,而不是定义位置。实际开发中常结合 bind、箭头函数来稳定上下文,避免意外指向。不复杂但容易忽略细节。

text=ZqhQzanResources