js的构造函数继承的几种类型

function animale(){

         this.species ="猫科";

}

function cat(){

       this.name=name;  

       this.color=color

}

1:基于apply()方法和call()方法

在子元素中加入一行代码

function cat(){

      this.name=name;

      this.color=color;

      animale.apply(this,arguments);  //这里的this就是指当前调用对象

}

var cat1=new cat("大黄","白色");

var cat2=new cat("戈薇","灰色");

console.log(cat1.species);

console.log(cat2.species);

缺点:不能调用父类原型类中的方法和属性

eg:animale.prototype.show=function(){alert(this.color)}

cat1.show();>-----undefined

2:基于原型的继承

cat.prototype=new animale();  //定义玩这句后cat.prototype.constructor就指向了animale

cat.prototype.constructor=cat;

var cat3 =new cat("大黄","白色");

var cat2=new cat("戈薇","灰色");

console.log(cat2.species);

//可以访问animale原型中的方法和属性,但是不能直接访问父类的构造函数,第一代改变了父类的引用类型的值,其他的子代也会改变,但基本类型的值不会随着改变。

eg:cat3.species="犬科";

console.log(cat2.species);   >-----猫科

3:利用空媒介进行封装处理(基于直接用原型继承的改变)

我们将不需要变化的数据放到父类 的原型里面

animale.prototype.species="猫科"

function f(){}   //空函数,F是空对象,所以几乎不占内存

f.prototype=animale.prototype; 

cat.prototype = new f();

cat.prototype.constructor =cat;

我们在把上述代码通过一个函数进行封装

function excent(child,parent){

     var F=function(){}

     F.prototype=parent.prototype;

     child.prototype=new F();

     child.prototype.constructor=child;

}

excent(cat,animale);

var cat1 = new Cat("大毛","黄色");

  alert(cat1.species); // 动物

posted @ 2016-11-02 16:13  爱笑的才  阅读(1036)  评论(0编辑  收藏  举报