JavaScript 中 this 指向规则详解与代码示例

作者:纸飞机

时间:2026-10-24

浏览:544

本文详细解析 JavaScript 中 this 关键字在不同执行环境下的指向规则。涵盖全局环境、普通函数、构造函数、箭头函数及对象方法的 this 行为,并深入讲解 call、apply 和 bind 方法如何改变 this 绑定。通过具体代码示例,对比正常模式与严格模式的差异,帮助开发者准确掌握 this 的机制。

文章目录

总结

  • 全局环境 ➡️ window
  • 普通函数 ➡️ window 或 undefined
  • 构造函数 ➡️ 构造出来的实例
  • 箭头函数 ➡️ 定义时外层作用域中的 this
  • 对象的方法 ➡️ 该对象
  • call()、apply()、bind() ➡️ 第一个参数

全局环境

无论是否处于严格模式,全局上下文中的 this 始终指向 window 对象。


console.log(this === window)  // true

// 严格模式
'use strict'
console.log(this === window)  // true

普通函数

  1. 正常模式
    • 在非严格模式下,普通函数内部的 this 指向 window 对象。
    • 
      function test() {
        return this === window
      }
      
      console.log(test())  // true
      
  2. 严格模式
    • 在严格模式下,普通函数内部的 this 值为 undefined。
    • 
      // 严格模式
      'use strict'
      
      function test() {
        return this === undefined
      }
      
      console.log(test())  // true
      

构造函数

当函数作为构造函数被调用时,this 指向新创建的实例对象。


function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

箭头函数

箭头函数没有自己的 this,其内部的 this 继承自定义时外层作用域的 this 值。


let test = () => {
  return this === window
}

console.log(test())  // true

let obj = {
  number: 1
}

function foo() {
  return () => {
    return this.number
  }
}

let test = foo.call(obj)

console.log(test())  // 1

对象的方法

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


let obj = {
  number: 1,
  getNumber() {
    return this.number
  }
}

console.log(obj.getNumber())  // 1

call()、apply()、bind()

  • 调用函数的 call() 或 apply() 方法时,该函数内部的 this 被绑定为传入的第一个参数。
  • 调用函数的 bind() 方法时,返回的新函数内部的 this 被绑定为传入的第一个参数。

let obj = {
  number: 1
}

function test(num) {
  return this.number + num
}

console.log(test.call(obj, 1))  // 2

console.log(test.apply(obj, [2]))  // 3

let foo = test.bind(obj, 3)
console.log(foo())  // 4

到此这篇关于JavaScript 中this指向问题案例详解的文章就介绍到这了,更多相关JavaScript 中this指向问题内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章