JavaScript提供一些函数来处理函数this指向问题,常用的有bind()、call()、apply()

call

call(objArgs,arg1,arg2..)
call第一个参数传的就是要指向的对象,后面参数是对应调用函数入参

function Person(name,age){
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log(this.name);
    }
}
let ming = new Person("ming",18);
let xiong = new Person("xiong",19);
ming.say.call(xiong);//xiong

apply()

apply(thisArg,[agrs])
与call相比,入参为数组

function Person(name,age){
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log(this.name);
    }
    this.talk = function(name){
        console.log(this.name +'talk to '+name );
    }
}

let ming = new Person("ming",18);
let xiong = new Person("xiong",19);

ming.say.apply(xiong);//xiong
//常用用法
let arr=[1,2,3,45];
let max = Math.max.apply(Math,arr);

bind

bind()方法不会调用函数,但是能改变函数内部this指向
bind(thisArg,arg1,arg2,...)

  • 返回由指定的this值和初始化参数改造的原函数的拷贝
function Person(name,age){
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log(this.name);
    }
    this.talk = function(name){
        console.log(this.name +'talk to '+name );
    }
}

let ming = new Person("ming",18);
let xiong = new Person("xiong",19);

let f = ming.say.bind(xiong);
f();//xiong

奶粥
6 声望0 粉丝

xiao海无涯苦揍舟~