call 和apply可以改变this的指向,借用别人的函数实现自己的功能.区别是传递的参数不同,call 需要把形参的顺序传到实参中,apply只能传递一个array

为什么要改变this的内存指向(其他对象的内存空间赋值给this)

我们程序开发中大部分是和别人一起开发,有时候别人开发了同样的代码我们其实不需要去重复写了,直接拿过来用就好了,这样公司可以节省开发成本,其次就是自己有定义好的代码不需要再重新copy了。直接让另一个对象使用就好了,那怎么才能拿过来呢?我们就需要考虑继承,首先想到的就是原型链,原型链会引入很多无用的东西,在正式开发不建议使用。然后就想到call可以改变this的指向,正好符合我们的需求

怎么使用call

构造函数.call(对象)
例子:

  1. function Car (color){
  2. this.color = color,
  3. this.name = "BMW",
  4. this.width ="1400",
  5. this.health=100,
  6. this.run =function(){
  7. this.health--;
  8. }
  9. }
  10. var car = new Car('red');
  11. var car1 = new Car('green');
  12. var person ={
  13. }
  14. Car.call(person,“black”)

这里通过call把Car构造函数的this的内存空间指向了person,就成功的创建了perosn对象

实现原理

首先需要知道的是我们平时调用函数都是函数名(),其实这是简写,正常是函数名.call()。
所以我们对象.call(需要生成的对象),然后对象回去寻找我的this到底是谁(通过看参数判断)。

项目中遇到的场景

  1. function Person (name,age,sex){
  2. this.name =name;
  3. this.age = age;
  4. this.sex =sex;
  5. }
  6. function Student(name,age,sex,tel){
  7. Person.call(this,name,age,sex);
  8. this.tel =tel;
  9. }
  10. var student = new Student("taowuhua","18","male",13552982091)

apply的使用

  1. function Person (name,age,sex){
  2. this.name =name;
  3. this.age = age;
  4. this.sex =sex;
  5. }
  6. function Student(name,age,sex,tel){
  7. Person.apply(this,[name,age,sex]);
  8. this.tel =tel;
  9. }
  10. var student = new Student("taowuhua","18","male",13552982091)