apply,call,bind方法总结:
1、apply()方法
apply的使用语法:
函数名字.apply(对象,[参数1,参数2,...]);
方法名字.apply(对象,[参数1,参数2,...]);
function Person(age,sex) {
this.age=age;
this.sex=sex;
}
Person.prototype.sayHi=function () {
console.log("您好啊:"+this.sex);
return 1000;
}
var per=new Person(10,"男");
per.sayHi(); //您好啊:男
function Student(name,sex) {
this.name=name;
this.sex=sex;
}
var stu=new Student("小明","男");
var r1=per.sayHi.apply(stu,[10,20]); //您好啊:男
console.log(r1); //1000
2、call()方法
call的使用语法
函数名字.call(对象,参数1,参数2,...);
方法名字.call(对象,参数1,参数2,...);
function Person(age) {
this.age=age;
}
Person.prototype.sayHi=function (x,y) {
console.log((x+y)+"===>"+this.age);
return 1000;
}
function Student(age) {
this.age=age;
}
var per = new Person(10);
var stu = new Student(12);
per.sayHi.call(stu,10,20);//30===>12
//this的指向从Person变成了Student
只要是想使用别的对象的方法,并且希望这个方法是当前对象的,
那么就可以使用apply或者是call的方法改变this的指向。
3、bind()方法
函数名字.bind(对象,参数1,参数2,...);---->返回值是复制之后的这个函数
方法名字.bind(对象,参数1,参数2,...);---->返回值是复制之后的这个方法
function Person(age) {
this.age=age;
}
Person.prototype.play=function () {
console.log(this+"==>"+this.age);
};
function Student(age) {
this.age=age;
}
var per = new Person(10);
var stu = new Student(20);
var ff=per.play.bind(stu); //bind方法,是复制一份的时候,改变了this的指向
ff();//[object Object]==>20
总结
- apply,call,bind 都可以改变this的指向;
- apply和call,bind的参数传递方式不一样;
- apply和call是调用的时候改变this指向;
- bind方法,是复制一份的时候,改变了this的指向;