想象this就像一个指针,
指向"当前正在执行的主角"。不同场景下,主角会变化——
有时是对象自己,有时是全局环境,还有时完全取决于谁在调用
对象方法调用
const person = {
name: "张三",
greet: function() {
return "你好,我是" + this.name
}
}
person.greet()
person 对象
name: "张三"
greet: function() { ... }
{{ methodCallResult }}
规则:对象方法
通过对象调用方法时,this 指向该对象
普通函数调用
function show() {
return this === window
}
show()
this = {{ strictMode ? 'undefined' : 'window' }}
规则:普通函数
非严格模式:this 指向全局对象
严格模式:this 是 undefined
构造函数调用
function Person(name) {
this.name = name
}
const p1 = new Person("李四")
const p2 = new Person("王五")
1
创建新对象
↓
2
this 指向新对象
↓
3
执行构造函数
↓
4
返回新对象
规则:new 调用
使用 new 调用函数时,this 指向新创建的对象
显式绑定 (call/apply/bind)
function greet() {
return "我是" + this.name
}
const person = { name: "小明" }
greet.call(person)
greet.apply(person)
const bound = greet.bind(person)
call(person)
立即调用,this → person
apply(person)
同 call,参数为数组
bind(person)
返回新函数,this 固定
{{ bindingResult }}
规则:显式绑定
call/apply/bind 可以显式指定 this 的指向
箭头函数的 this
const person = {
name: "小红",
greet: function() {
setTimeout(() => {
console.log(this.name)
}, 1000)
}
}
person.greet()
规则:箭头函数
箭头函数没有自己的 this,它继承外层作用域的 this
📋 this 指向速查表
obj.method()
obj
func()
window / undefined
new Func()
新创建的对象
func.call(obj)
obj
箭头函数
外层作用域的 this
💡
核心思想:
this 的值是在函数调用时确定的,不是定义时确定的。关键要看"函数是如何被调用的",而不是"函数在哪里定义"。箭头函数是例外——它没有自己的 this,从外层作用域继承。