js中this的指向问题

文章类型:Javascript

发布者:hp

发布时间:2025-04-18

一:基本使用

1:全局作用域=>非严格模式下,this 指向全局对象(浏览器中为 window,Node.js 中为 global),严格模式下为 undefined

console.log(this === window); // true(非严格模式)

2:普通函数调用=>非严格模式下 this 默认绑定到全局对象;严格模式下为 undefined

function fn() { console.log(this); }
fn(); // window(非严格模式) | undefined(严格模式)

3:对象方法调用=>this 指向调用该方法的对象‌

const obj = { name: 'LiMing', say() { console.log(this.name); } };
obj.say(); // "LiMing"(this 指向 obj)

二:特殊使用

1:构造函数调用=>使用 new 创建实例时,this 指向新生成的对象‌

function Person() { this.name = 'John'; }
const p = new Person(); // this 指向 p

2:箭头函数=>this 继承外层作用域的 this,且不可被 call/apply/bind 修改‌

const obj = { 
  fn: function() { 
    setTimeout(() => console.log(this), 100); // this 指向 obj(外层作用域)
  }
};

3:显示绑定=>使用 call/apply/bind 强制指定 this 指向‌

function fn() { console.log(this); }
const ctx = { id: 100 };
fn.call(ctx); // ctx(this 被显式绑定)

三:其他用法

1:事件处理器=>DOM 事件处理函数中的 this 指向触发事件的元素‌

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

2:严格模式下=>独立调用的函数中的 this 为 undefined,全局作用域仍指向 window

"use strict";
function test() { console.log(this); }
test(); // undefined

四:总结

this 绑定优先级从高到低=>new 绑定‌ > ‌显式绑定(call/apply/bind)‌ > ‌隐式绑定(对象方法)‌ > ‌默认绑定(全局或 undefined)