JavaScript中apply和call的作用和区别
apply的使用语法:
- 函数名字.apply(对象,[参数1, 参数2, …]);
- 方法名字.apply(对象,[参数1, 参数2, …]);
call的使用语法
- 函数名字.call(对象,参数1, 参数2, …);
- 方法名字.call(对象,参数1, 参数2, …);
它们的作用:
- 改变this的指向
- 只要想使用别的对象方法,并且希望这个方法是当前对象的,那么就可以使用apply或者是call的方法改变this的指向
区别: 参数传递的方式不一样
案例:
function Person(age,sex) {
this.age=age;
this.sex=sex;
}
//通过原型添加方法
Person.prototype.sayHi=function (x,y) {
console.log("hello,"+this.sex); //hello,Gary
return 1000;
};
var per=new Person(10,"男");
per.sayHi();
console.log("-----------");
function Student(name,sex) {
this.name=name;
this.sex=sex;
}
var stu=new Student("Jack","Gary");
var r1=per.sayHi.apply(stu,[10,20]);
var r2=per.sayHi.call(stu,10,20);
console.log(r1); //1000
console.log(r2); //1000