码迷,mamicode.com
首页 > 编程语言 > 详细

javascript继承

时间:2017-05-25 20:43:05      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:属性   调用   实现   继承   style   prot   rip   函数   类型   

经典继承

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

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

 

javascript继承

标签:属性   调用   实现   继承   style   prot   rip   函数   类型   

原文地址:http://www.cnblogs.com/wz27ufo/p/6905570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!