this指向问题
关于这篇以前的博客也有写过,这个就想是做一个补充可以先来看看前面写的
this
关于this指向,总结来说就是指向是由调用对象决定,而不是定义决定
let show = function() {
console.log(this);
}
我们以这段代码为例
普通函数
show() // window
call、bind、apply改变this指向
show.call({ name: 'airhua' }) // 指向传入对象
show.bind({ name: 'air' })() // 指向传入对象
在对象中
const person = {
name: 'airhua',
sayHi() {
console.log(this); // 当前对象
},
wait() {
setTimeout(function() {
console.log(this); // window
})
}
}
person.wait()
而当setTimeout
传入函数改成箭头函数:
const person = {
name: 'airhua',
sayHi() {
console.log(this); // 当前对象
},
wait() {
setTimeout(() => {
console.log(this); // 当前对象
})
}
}
// 箭头函数this指向上级作用域this
person.wait()
- 开始在对象
wait
函数里面应该是指向当前对象,但是setTimeout
传入函数就类似调用普通函数,普通函数里面this
指向就在全局了 - 而箭头函数
this
指向上级作用域this
手写一个bind实现
// fn1.__proto__ === Function.prototype
function fn1(a, b) {
console.log(this);
console.log(a, b);
return a + b
}
Function.prototype.bind1 = function() {
// 参数拆解为数组
const args = Array.prototype.slice.call(arguments)
// 获取this
const t = args.shift()
// fn1.bind(...) 中的fn1
const self = this
return function() {
return self.apply(t, args)
}
}
const fn2 = fn1.bind1({ name: 'airhua' }, 10, 20)
console.log(fn2());