javascript继承

经典继承

借用构造函数,子类型构造函数内部调用超类型构造函数

function SuperType(){

  this.colors = ["red","blue","green"]; 

}

function SubType(){

  SuperType.call(this);   //继承了SuperType

}

var instance1 = new SubType();

instance1.colors.push("black");

alert(instance1.colors);  //"red,blue,green"

var instance2 = new SubType();

alert(instance1.colors);        //"red,blue,green"

 

组合继承

将原型链和借用构造函数的技术组合到一起的继承模式,使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承,即通过在原型上定义方法实现了函数复用,又能保证每个实例都有它自已的属性。

function SuperType(name){

  this.name = name;

  this.colors = ["red","blue","green"];

}

SuperType.prototype.sayName = function(){

  alert(this.name);

}

function SubType(name,age){

  SuperType.call(this,name);//继承属性

  this.age = age;

}

SubType.prototype = new SuperType();//继承方法

SubType.prototype.sayAge = function(){

  alert(this.age);

}

var instance1 = new SubType("Nicholas",29);

instance1.colors.push("black");

alert(instance1.colors);  //"red,blue,green,black"

instance1.sayName();  //"Nicholas"

instance1.sayAge();  //29

 

var instance2 = new SubType("Greg",27);

alert(instance2.colors);  //"red,blue,green"

instance2.sayName();  //"Greg"

instance2.sayAge();  //27

 

posted @ 2017-05-25 19:33  宝宝少少  阅读(92)  评论(0编辑  收藏  举报