JS 中改变函数的this
指向,call
,apply
,bind
方法的使用和区别
1. call()
方法 文档说明
语法
function.call(thisArg, arg1, arg2, ...)
thisArg
是想要将this
指向的那个对象或者方法arg1,arg2...
传递的参数
使用,使用call
之后函数会立即调用
- 在没有使用
call
的时候fn
函数中的this
指向的是window
function fn(a , b) { console.log(this) // window console.log(a + b) // 4 } fn(2,2)
- 使用
call
之后,函数会立即执行,fn
函数中的this
指向被改变,指向了obj
对象const obj = { name: "小火车" } function fn(a , b) { console.log(this) // obj console.log(a + b) // 4 } fn.call(obj,2,2)
- 常用在组合继承中改变
this
指向function Father(name,age) { this.name = name, this.age = age } Father.prototype.sing =function(){ console.log("我会唱歌") } function Son(name,age) { Father.call(this,name,age) } const user = new Son("小火车",24) console.log(user.name) // 小火车
2.apply()
方法 文档说明
语法
func.apply(thisArg, [argsArray])
thisArg
是想要将this
指向的那个对象或者方法argsArray
一个数组或者类数组对象
使用,使用apply
之后函数也会立即调用
- 在没有使用
apply
的时候fn
函数中的this
指向的是window
function fn(a , b) { console.log(this) // window console.log(a + b) // 4 } fn(2,2)
- 使用
apply
之后,函数会立即执行,fn
函数中的this
指向被改变,指向了obj
对象const obj = { name: "小火车" } function fn(a,b) { console.log(this) // obj console.log(a + b) // 4 } fn.apply(obj,[2,2])
- 常结合数组一起使用,可以直接使用一些方法寻找数组的最大值最小值等等
const array = [1,88,51,2] let max = Math.max.apply(Math,array) console.log(max) // 88
3. bind()
方法 文档说明
语法
function.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg
是想要将this
指向的那个对象或者方法arg1,arg2...
传递的参数
使用,使用bind()
方法之后函数不会立即执行,但是bind()
方法是使用最多的改变this
指向
- 在没有使用
bind
的时候fn
函数中的this
指向的是window
function fn(a , b) { console.log(this) // window console.log(a + b) // 4 } fn(2,2)
- 使用
bind
之后,函数会立即执行,fn
函数中的this
指向被改变,指向了obj
对象const obj = { name: "小火车" } function fn(a,b) { console.log(this) // obj console.log(a + b) // 4 } const getFn = fn.bind(obj,2,2) getFn()
- 使用,结合
setTimeout
,比如按钮点击之后变成不可点击,三秒之后还原const btn = document.querySelector("button") btn.onclick = function() { this.disabled = true setTimeout(function(){ this.disabled = false }.bind(this), 3000); }
- 因为
bind()
方法返回的就是一个函数,并且也不会立即执行,因此可以在计时器时间到之后再执行
三者之间的关系
共同点
- 都可以改变
this
的指向
区别
call
和apply
会立即调用函数,并且改变函数内部的this
指向call
和apply
传递的参数不同,call
参数的形式是arg1, arg2, ...
,apply
参数的形式必须是[arg1,arg2,...]
bind
不会立即调用函数,可以改变函数内部的this
指向
使用场景
call
常用于组合继承apply
经常和数组关联,借助一些函数得到数组的最大值最小值bind
一般改变定时器内部的this
指向