改变函数this指向的方法
- call
- apply
- bind
call方法
call方法可以进行函数的调用,同时也可以改变this的指向,传递参数的方法为直接传递。
示例代码:
函数调用
function test(){
console.log("测试代码");
}
test.call()
改变this指向
var o={
name:"123"
}
function fn(){
console.log(this);
}
fn.call(o)
call实现继承
//call实现继承
function Start(name, age) {
this.name = name
this.age = age
}
function Person(name, age) {
Start.call(this, "ZYY", 18)
}
let p = new Person()
console.log(p.name);
apply方法
apply 也能执行函数并改变this
var o = {
name: "123"
}
function fn(arr1, arr2) {
console.log(this);
console.log(arr1);
console.log(arr2);
}
fn.apply(o, ["zyy", "xdx"])
Math.max() 返回一组数字中的最大值,可以利用apply,首先不改变this的指向,然后传入数组,数组中的每一个数会被单独作为参数放进Math.max中
//Math.max.apply(null,[10,52,30,16])
//等价于
//Math.max(10,52,30,16)
var max1 = Math.max.apply(Math, [10, 52, 30, 16])
var max2 = Math.max(10, 52, 30, 16)
console.log(max1);
console.log(max2);
bind方法
bind方法 可以改变this指向 但不调用函数 返回的是一个改变this指向后的函数
需求,点击按钮后禁用,3s后启用
<button>按钮</button>
var btn = document.querySelector("#btn")
btn.onclick = function () {
this.disabled = true
setTimeout(function(){
this.disabled=false //因为定时器中的this默认指向window,所以这种方法无效
},3000)
// 方法一
var that=this//定义一个that接收事件this
setTimeout(function(){
that.disabled=false
}, 3000);
//方法二
setTimeout(function(){
this.disabled=false
}.bind(this), 3000); //改变定时器函数的this
}
总结
相同点:
都可以改变函数内部的this指向.
区别点:
call 和 apply 会调用函数, 并且改变函数内部this指向.
call 和 apply 传递的参数不一样, call 传递参数 aru1, aru2…形式 apply 必须数组形式[arg]
bind 不会调用函数, 可以改变函数内部this指向.
主要应用场景:
call 经常做继承.
apply 经常跟数组有关系. 比如借助于数学对象实现数组最大值最小值
bind 不调用函数,但是还想改变this指向. 比如改变定时器内部的this指向.