JavaScript 中 this 的指向规则是什么?
this 的指向取决于函数的调用方式,有 4 种绑定规则:
1. 默认绑定(独立调用)
function foo() { console.log(this) }
foo() // 非严格模式:window;严格模式:undefined2. 隐式绑定(作为对象方法)
const obj = {
name: 'Tom',
sayHi() { console.log(this.name) }
}
obj.sayHi() // 'Tom'(this → obj)
// 隐式丢失
const fn = obj.sayHi
fn() // undefined(this → window/undefined)3. 显式绑定(call/apply/bind)
function greet(greeting) {
console.log(greeting + ', ' + this.name)
}
const person = { name: 'Tom' }
greet.call(person, 'Hi') // 'Hi, Tom'
greet.apply(person, ['Hi']) // 'Hi, Tom'
const bound = greet.bind(person, 'Hi')
bound() // 'Hi, Tom'4. new 绑定
function Person(name) {
this.name = name // this → 新创建的对象
}
new Person('Tom')优先级
new > 显式绑定 > 隐式绑定 > 默认绑定
箭头函数(特殊)
箭头函数没有自己的 this,继承外层作用域的 this,且不可被 call/apply/bind 修改:
const obj = {
name: 'Tom',
arrow: () => console.log(this.name),
normal() { console.log(this.name) }
}
obj.arrow() // undefined 或 '' (this → 外层 window)
obj.normal() // 'Tom'