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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。