理解 this:四条绑定规则
理解 this:四条绑定规则
this 是 JS 最容易误解的机制:它是在函数调用时确定的,跟函数定义的位置没有关系。按优先级从高到低有四条绑定规则。
1. new 绑定
function Person(name) {
this.name = name
}
const p = new Person('Dong')
// this 指向新创建的对象 p
2. 显式绑定:call / apply / bind
function greet() {
console.log(this.name)
}
const user = { name: 'Dong' }
greet.call(user) // 立即调用,this = user
greet.apply(user) // 同 call,参数以数组传入
const fn = greet.bind(user) // 返回一个 this 永久绑定的新函数
fn()
3. 隐式绑定:谁调用就指向谁
const obj = {
name: 'obj',
greet() { console.log(this.name) },
}
obj.greet() // this = obj
坑在引用丢失:把方法取出来单独调用,this 就不再是 obj:
const g = obj.greet
g() // this → undefined(严格模式)或 window
定时器、回调函数里也常丢 this,解决办法:箭头函数或 bind。
4. 默认绑定
独立调用函数、前面没有任何修饰时,严格模式下 this === undefined,非严格模式指向全局对象。
特殊规则:箭头函数
箭头函数没有自己的 this,它捕获外层作用域的 this,且 call/apply/bind 改不了:
function Timer() {
this.seconds = 0
setInterval(() => this.seconds++, 1000) // this 始终是 Timer 实例
}
判断 this 的口诀:先看 new,再看 call/apply/bind,再看调用的点号前面是谁,最后是默认值;箭头函数直接找外层。
看到这里了?如果这篇文章帮到过你
请我喝瓶可乐就好 🥤

评论0 条
还没有评论,来抢沙发~