call、apply、bind使用和区别
1、call作用:
语法: fun.call(thisArg, arg1,arg2, …)
thisArg: fun函数运行时指定的this值; arg1,arg2参数;返回值是函数的返回值
1.调用函数
2.改变this指向
const obj = {name: 'red'}
function fn(x, y) {
console.log(this)
console.log(x+y) // 3
}
fn.call() // 此时this指向为window
fn.call(obj, 1, 2) //此时this指向为obj
2、apply作用:
语法: fun.apply(thisArg, [argsArray])
thisArg: fun函数运行时指定的this值;argsArray数组参数,传递的值必须在数组里面;返回值是函数的返回值
1.调用函数
2.改变this指向
const obj = {name: 'red'}
function fn(x, y) {
console.log(this)
console.log(x+y) // 3
}
fn.apply() // 此时this指向为window
fn.apply(obj, [1, 2]) //此时this指向为obj
apply主要和数组有关系,可以使用Math.max()求数组最大值等
// const max = Math.max(1, 2, 3)
const max = Math.max.apply(Math, [1,2,3])
3、bind作用:
语法:fun.bind(thisArg, arg1, arg2, …)
thisArg: fun函数运行时指定的this值;arg1, arg2传递的参数;返回值是拷贝后的新函数,且this更改过
注意:不会调用函数,但是可以改变this指向
const obj = {name: 'tiger'}
function fn() {
console.log(this)
}
const fun = fn.bind(obj)
console.log(fun) // 打印出来是fn()函数,但是this指向obj
fun()
总结:
相同点:
三者都可以改变this的指向
不同点:
call和apply 可以调用函数
call和apply,传递的参数不同,call是以arg1,arg2形式传递,apply是以数组形式传递[argsArr]
bind不会调用函数