JavaScript 中 this 指向规则详解与代码示例
作者:纸飞机时间:2026-10-24 15:06:51浏览:545
本文详细解析 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
普通函数
- 正常模式
- 在非严格模式下,普通函数内部的 this 指向 window 对象。
function test() { return this === window } console.log(test()) // true - 严格模式
- 在严格模式下,普通函数内部的 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指向问题内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
作者最新文章
JS动态构建复杂嵌套JSON对象的方法
2026-11-05 15:41:52
JS负数取余为什么是负数?详解余数与模运算区别
2026-11-05 13:34:41
JS 解压出现乱码或报错怎么解决?
2026-11-05 12:32:38
JS 中 startsWith、indexOf 与正则判断字符串前缀的对比
2026-11-04 22:19:43
JS解析Excel后怎么将数据转换为JSON格式
2026-11-04 20:58:28
