[toc]
默认绑定时,使用严格模式,不能将全局对象用于默认绑定,
this
会绑定到undefined
function say(){
console.log(this)
}
say() // window
function say(){
'use strict'
console.log(this)
}
say() // undefined
当函数引用有上下文对象时,隐式绑定会把函数调用中的 this 绑定到这个上下文对象
function say(){
console.log(this.name)
}
const person = {
name: 'tmchw',
say,
}
function createBoy() {
return person
}
const boy = createBoy()
boy.say() // tmchw
person.say() // tmchw
function say(){
console.log(this.name)
}
const person = {
name: 'tmchw',
say,
}
const talk = person.say
talk() // undefined
// talk 实际上引用的 say 函数本身,所以应用了默认绑定,这是的 this 指向 window
function say(){
console.log(this.name)
}
function talk(fn){
fn()
}
const person = {
name: 'tmchw',
say,
}
talk(person.say) // undefined
// 参数传递,其实也是一种隐式赋值,逻辑和「引用赋值隐式丢失」一样
调用函数时,强制响函数绑定到
this
,可以通过call
、apply
、bind
方法实现
new 绑定 > 显示绑定 > 隐式绑定 > 默认绑定