深度剖析 javascript call方法实现继承的原理

call 方法是比常常见也是javascript 难点之一,以前只知道可以实现继承,但是没有深度研究过原理,网上大多数也只是说了方法,没有讲其中的原理,
今天没事正好好好研究一下。
call 方法最常见的也是面试问题之一是啥,对就是用call实现继承。
以下是两个简单的实现继承的例子。

 demo1:
     function a(){
       this.name = function(){
          console.log('a',this.namevalue,this.age)
     }
  }
function b(){

    a.call(this);    //这里的this代表b对象本身

}
var bt = new b();

b.name(); 

demo2:

     function Product(name, price) {
      this.name = name;
     this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

我们可以看到,只需要在b中 运行 a.call(this);就可以实现继承了,可是为什么呢?

我们先看下官方文档对call方法的解释:

call() 提供新的 this 值给当前调用的函数/方法。

也就是说call 方法将原本a的this对象替换成了b的this对象,是不是有点绕口?

但是这样还是不能解释为什么bt 可以访问a函数内的方法,a函数内的方法只有a的实例才可以访问呀,难道a函数也被实例化了嘛????

要搞清楚这个问题我们首先还需要知道new 这个关键字到底做了什么?

function b(){
this.name="b";
this.sayName=()=>{
console.log('this.name',this.name);
}
}
var b=new b();

console.log(b);
深度剖析 javascript call方法实现继承的原理

我们可以看到new 关键字创建了一个对象,将所有this关键字的属性都生成了新对象的属性;
也就是说new关键字会将所有的和this有关的属性都会转化为新对象的属性,
那么当call方法将b的this对象赋值给a方法时,new 也会检测到:并且当做是b的属性一期实例化:让我们来试验一下。已demo1代码为例,将b输出一下:

function a(){
    this.namevalue=19;
    this.name = function(){
      console.log('a',this.namevalue,this.age)
    }
}
function b(){
    this.age=19;
    a.call(this);    //这里的this代表b对象本身

}
var bs = new b();
console.log(bs)

输出:

深度剖析 javascript call方法实现继承的原理

猜测正确,所以实现继承的方式call只是起了个替换this对象的作用,主要工作还是在new 关键字,它能自动检测和this绑定的属性,全部添加到要实例化的对象上面。其实上面的代码和下面的代码效果是一样的:

function b(){
    this.namevalue=19;
    this.name = function(){
      console.log('a',this.namevalue,this.age)
    }
    this.age=19;
    a.call(this);    //这里的this代表b对象本身

}
var bs = new b();
console.log(bs)

深度剖析 javascript call方法实现继承的原理

今天算是对call 有了更深的理解,完全是自我理解,如果你有不同的见解,欢迎评论,欢迎打脸指正。

猜你喜欢

转载自blog.51cto.com/13496570/2411590
今日推荐