继承 第二天

继承是面向对象的一个核心概念,其他主要面向对象的继承主要靠两种方式实现继承 一种是继承 另一种是接口实现 

一.原型继承

  function Box(){

           this.name=‘lll’;                       //被继承的函数叫做超类型(父类型 基类)

}

   function Desk(){                              //继承的函数叫做子类型(子类,派生类)

                  this.age=100;
}


Desk.prototype=new Box();

var desk=new Desk();

alert(desk.name);

function Table(){

this.address='lol';
}

Table.prototype=new Desk();

var table=new Table();
alert(table.name);

 原型继承示意图 

Desk 的原型获得是Box()的实例和原型  以此类推

   就近元则:先查询实例有没有该属性 ,然后在查找原型里面是否还有该属性

alert(desk instanceof Box)     true

  

二.借用构造函数(对象冒充函数)

解决引用共享和超类型传参数的问题

functon Box(name,age){
this.name=name;
this.age=age;
 //this.family=['哥哥','姐姐','弟弟']
}

Box.prototype.family='家庭';
function Desk(){

Box.call(this,'lll',100);

}

var desk=new Desk();
alert(desk.name);
alert(desk.family) 对象冒充解决了共享问题和传参数的问题 但是只能继承实例的问题 不能继承原型 方法放在构造里,浪费空间,每次实例化都分配地址

 


三.组合继承(对象冒充继承和原型继承)

functon Box(name,age){
this.name=name;
this.age=age;
 //this.family=['哥哥','姐姐','弟弟']
}

Box.prototype.run(){

  return this.name+this.age;

}



function Desk(){

Box.call(this,'lll',100);

}


Desk.prototype=new Box();


var desk=new Desk();
alert(desk.name);
alert(desk.family)  
alert(desk.run())

  


四.原型继承

function obj(0){                                     //中转函数

   function F(){}     用来存储传递过来的对象
  F.prototype=o;
  return  new F();

}




var box={

     name:'lll';
     age:100;
family:['哥哥' ,'姐姐'] } var box1=obj(box) box1 等于new F(); alert(box1.family);
box1.push('弟弟')
alert(box1.family);

var box2=obj(box);
alert(box2.family); 引用类型属性共享了

  

五.寄生式继承(原型加工厂模式)

function obj(o){                                     //中转函数

   function F(){}     用来存储传递过来的对象
  F.prototype=o;
  return  new F();

}

  function create(o){                   //寄生式继承

var f=obj(o);
f.run=function(){

return this.name
}
return f;
} var box={ name:'lll'; age:100; family:['哥哥' ,'姐姐'] }
var box1=create(box);
alert(box1.name)

  


六寄生组合继承

function create(box, desk) {
	var f = obj(box.prototype);
	f.constructor = desk;				//调整原型构造指针
	desk.prototype = f;
}

function Box(name, age) {
	this.name = name;
	this.age = age;
}

Box.prototype.run = function () {
	return this.name + this.age + '运行中...'
}

function Desk(name, age) {
	Box.call(this, name, age);				//对象冒充
}

//通过寄生组合继承来实现继承
create(Box, Desk);							//这句话用来替代Desk.prototype = new Box();


var desk = new Desk('Lee', 100);
alert(desk.run());
alert(desk.constructor);

  


原文地址:https://www.cnblogs.com/france-008/p/5839014.html