登录
首页 >  文章 >  前端

JavaScript中this指向怎么确定?常见场景解析

时间:2026-01-21 19:45:46 376浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习文章的朋友们,也希望在阅读本文《JavaScript中this指向怎么确定?常见场景有哪些》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新文章相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

JavaScript中this指向取决于调用方式而非定义方式:谁调用函数,this就指向谁(箭头函数除外,它继承外层this)。

javascript中this指向如何确定_常见场景有哪些

JavaScript 中 this 的指向不是看函数怎么定义的,而是看它**怎么被调用的**。核心规则只有一条:谁调用函数,this 就指向谁(箭头函数除外,它不绑定自己的 this,而是继承外层作用域的)。下面分常见场景说明。

普通函数直接调用(非严格模式 vs 严格模式)

在全局作用域下直接写 fn() 调用函数:

  • 非严格模式:this 指向 window(浏览器)或 globalThis(Node.js)
  • 严格模式:this 是 undefined

对象方法调用(最典型场景)

当函数作为对象的属性被调用时,this 指向该对象:

const obj = {
  name: 'Alice',
  say() {
    console.log(this.name); // 'Alice'
  }
};
obj.say(); // this → obj

⚠️ 注意:一旦把方法单独提取出来,就丢失了绑定关系:

const fn = obj.say;
fn(); // this → window(非严格)或 undefined(严格)

call / apply / bind 显式绑定

这三个方法可以手动指定 this 值:

  • fn.call(obj, arg1, arg2) —— 立即执行,this 为 obj
  • fn.apply(obj, [arg1, arg2]) —— 同上,参数以数组传入
  • const boundFn = fn.bind(obj) —— 返回新函数,this 永远绑定为 obj

bind 绑定后无法被后续 call/apply 覆盖(除非 new 调用)。

构造函数调用(new 关键字)

new Fn() 调用时,this 指向新创建的实例对象:

function Person(name) {
  this.name = name; // this → 新生成的实例
}
const p = new Person('Bob');

此时即使函数内部有 call/apply,也不会影响 new 的 this 绑定(new 优先级最高)。

箭头函数(无独立 this)

箭头函数不绑定自己的 this,它会沿作用域链向上查找,使用外层普通函数或全局作用域的 this 值:

const obj = {
  name: 'Charlie',
  regular() {
    console.log(this.name); // 'Charlie'
    const arrow = () => console.log(this.name); // 也输出 'Charlie'
    arrow();
  }
};

因此箭头函数不能用作构造函数(不能 new),也不支持 call/apply/bind 改变 this。

事件处理函数中的 this

DOM 事件监听器中,回调函数的 this 默认指向触发事件的元素(即 event.currentTarget):

button.addEventListener('click', function() {
  console.log(this === button); // true
});

但如果用箭头函数,则 this 指向外层作用域,不再是 button:

button.addEventListener('click', () => {
  console.log(this === button); // false(通常是 window 或 undefined)
});

定时器与异步回调

setTimeout / setInterval 的回调函数属于普通函数调用,this 默认指向全局对象(非严格)或 undefined(严格):

const obj = {
  name: 'David',
  init() {
    setTimeout(function() {
      console.log(this.name); // undefined(严格模式)
    }, 100);
    // ✅ 正确做法:用箭头函数,或 bind,或存 this
    setTimeout(() => console.log(this.name), 100); // 'David'
  }
};

理解 this 的关键在于观察**调用位置和调用方式**,而不是函数定义的位置。多练习几种调用形式,再结合优先级(new > 显式绑定 > 对象方法 > 普通调用),基本就能准确判断了。

以上就是《JavaScript中this指向怎么确定?常见场景解析》的详细内容,更多关于的资料请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>