call 和apply可以改变this的指向,借用别人的函数实现自己的功能.区别是传递的参数不同,call 需要把形参的顺序传到实参中,apply只能传递一个array
为什么要改变this的内存指向(其他对象的内存空间赋值给this)
我们程序开发中大部分是和别人一起开发,有时候别人开发了同样的代码我们其实不需要去重复写了,直接拿过来用就好了,这样公司可以节省开发成本,其次就是自己有定义好的代码不需要再重新copy了。直接让另一个对象使用就好了,那怎么才能拿过来呢?我们就需要考虑继承,首先想到的就是原型链,原型链会引入很多无用的东西,在正式开发不建议使用。然后就想到call可以改变this的指向,正好符合我们的需求
怎么使用call
构造函数.call(对象)
例子:
function Car (color){
this.color = color,
this.name = "BMW",
this.width ="1400",
this.health=100,
this.run =function(){
this.health--;
}
}
var car = new Car('red');
var car1 = new Car('green');
var person ={
}
Car.call(person,“black”)
这里通过call把Car构造函数的this的内存空间指向了person,就成功的创建了perosn对象
实现原理
首先需要知道的是我们平时调用函数都是函数名(),其实这是简写,正常是函数名.call()。
所以我们对象.call(需要生成的对象),然后对象回去寻找我的this到底是谁(通过看参数判断)。
项目中遇到的场景
function Person (name,age,sex){
this.name =name;
this.age = age;
this.sex =sex;
}
function Student(name,age,sex,tel){
Person.call(this,name,age,sex);
this.tel =tel;
}
var student = new Student("taowuhua","18","male",13552982091)
apply的使用
function Person (name,age,sex){
this.name =name;
this.age = age;
this.sex =sex;
}
function Student(name,age,sex,tel){
Person.apply(this,[name,age,sex]);
this.tel =tel;
}
var student = new Student("taowuhua","18","male",13552982091)