第一种call
const obj = {
name: '科比',
age: 41
}
function fn(x,y) {
console.log(this) //this指向obj
console.log(x+y)
}
fn.call(obj,1,2)
第二种apply
const obj = {
name: '科比',
age: 41
}
function fn(x,y) {
console.log(this) //this指向obj
console.log(x+y)
}
fn.apply(obj,[1,2])
第三种bind
bind只会改变this指向,不会调用函数,返回值是个函数。
const obj = {
name: '科比',
age: 41
}
function fn(x,y) {
console.log(this) //this指向obj
console.log(x+y)
}
const fun = fn.bind(obj,1,2)
fun()
//有一个按钮,点击里面就禁用,2秒之后开启
document.querySelector('button').addEventListener('click',function(){
this.disabled = true
setTimeout(function(){
this.disabled = false
}.bind(this),2000)
})
//定时器this指向是window,在这里通过bind把this指向改成了button