改变函数内this指向的方法

1、call()

写法:fun.call(thisArg,arg1,arg2…)
作用:可以调用函数,还可以改变函数内的this指向

let o = {
	name:'andy',
}
function fn (a,b) {
    console.log(this);
    console.log(a + b);
}
fn.call(o,1,2);
// call的主要作用可以实现继承
function Father (uname,age,sex) {
    this.uname = uname;
    this.age = age;
    this.sex = sex;
}
function Son (uname,age,sex) {
	Father.call(this,uname,age,sex);
}
let son = new Son('刘德华',18,'男');
console.log(son);

2、apply()

作用:也是调用函数,也可以改变函数内部的this指向
注意点:它的参数必须是数组(伪数组)
主要应用:比如说我们可以利用 apply借助于数学内置对象求最大值

fun.apply(thisArg,arg1,arg2...)
let o = {
	name:'andy'
};
function fn (arr) {
    console.log(this);
    console.log(arr); // 'pink'
}
fn.apply(o,['pink']);
let arr = [1,66,5,49,78];
let max = Math.max.apply(Math,arr);
console.log(max);

3、bind()

写法:fun.bind(thisArg,arg1,arg2…)
作用:不会调用原来的函数,可以改变原来函数内部的this指向
返回的是原函数改变this之后产生的新函数
如果有的函数我们不需要立即调用,但是又想改变这个函数内部的this指向此时用bind
有一个按钮,当我们点击了之后,就禁用这个按钮,3秒钟之后开启这个按钮

let btn = document.querySelector('button');
btn.addEventListener('click',function(){
this.disabled = true; // 这个this指向的是btn按钮
    // let that = this;
	setTimeout(function(){
    // this.disabled = false; // 定时器里面的this指向的是window
       this.disabled = false; // 此时的this指向的是btn
   }.bind(this),3000) // 这个 this 指向的是btn这个对象
})

4、三种方法的总结

改变函数内this指向的方法

上一篇:jquery的点击事件驱动获取值


下一篇:Docker笔记7-Docker-compose