深入继承(精)

来源:互联网 发布:局域网免费聊天软件 编辑:程序博客网 时间:2024/05/16 01:55

http://blog.csdn.net/magneto7/article/details/25010555


/**
 * js实现继承:
 * 1.基于原型链的方式
 * 2.基于伪造的方式
 * 3.基于组合的方式
 */
一、基于原型链的方式
function Parent(){
  this.pv = "parent"; 
}
Parent.prototype.showParentValue = function(){
  console.log(this.pv); 
}

function Child(){
  this.cv = "child"; 
}
//让Child的原型链指向Parent,也就等于完成了一次继承
Child.prototype = new Parent();
Child.prototype.showChildValue = function(){
  console.log(this.cv); 
}

var c = new Child();
c.showParentValue(); //parent
c.showChildValue();  //child

/**
 *在使用原型链进行继承时,应注意以下问题:
 *1.不能在设定了原型链之后,再重新为原型链赋值
 *2.一定要在原型链赋值之后才能添加或者覆盖方法
 */
 
 
 
使用原型链继承的缺点是:
1.无法从子类中调用父类的构造函数,
2.如果父类中存在引用类型,这个引用类型会添加到子类的原型中,如果一个对象修改了这个引用,其它对象的引用同时修改

所以一般都不会单纯的使用原型链来实现继承。

二、基于伪造的方式
function Parent(){
  this.color = ["red","blue"]; 
}

function Child(){
  //在Child中的this应该是指向Child的对象
  //在调用Parent方法的时候,而且this又指向了Child,就等于是:this.color = ["red","blue"];
  //也就等于在Child中有了this.color属性,这样也就变向的完成了继承
  Parent.call(this); 
  //Parent(); 这种调用方式,只是完成了函数的调用,根本无法实现继承
}
var c1 = new Child();
c1.color.push = "green";
console.log(c1.color);  //red,blue,green
var c2 = new Child();
console.log(c2.color);  //red,blue

//但是这依然不太好,如下:
------------------------------------------------------------------------------
function Parent(name){
  this.color = ["red","blue"]; 
  this.name = name;
  
  /*this.say = function(){
     console.log(this.name);
  }*/
}
Parent.prototype.say = function(){
  console.log(this.name); 
}

function Child(name,age){
   /**
    * 使用伪造的方式就可以把子类的构造函数参数传递到父类中
    * 存在问题:
    *     1.由于使用的伪造方式,不会完成Child的原型指向Parent,所以对Child来说say方法不存在
    * 解决方案:
    *     将这个方法放到Parent中,使用this来创建
    * 但是这又引起前面提到的问题:
    *     每个Child对象都会有一个say,占用空间,所以也不应单独的使用伪造的方式实现继承。
    *     因此我们要使用组合的方式来解决这个问题
    */
  this.age = age;
  Parent.call(this,name); 
}
var c1 = new Child("Leon",13);
var c2 = new Child("Ada",22);
console.log(c1.name+","+c1.age);
console.log(c2.name+","+c2.age); 

三、基于组合的方式
组合的方式是:属性通过伪造的方式实现,方法通过原型链的方式实现。

function Parent(name){
  this.color = ["red","blue"];
  this.name = name;
}                    
Parent.prototype.ps = function(){
  console.log(this.name+",["+this.color+"]"); 
}         

function Child(name,age){
   this.age = age;
   Parent.call(this,name);
}
Child.prototype = new Parent();
Child.prototype.say = function(){
  console.log(this.name+","+this.age+",["+this.color+"]"); 
}

var c1 = new Child("Leon",22);
c1.color.push("green");
c1.say(); //Leon,22,[red,blue,green]
c1.ps();  //Leon,[red,blue,green]
var c2 = new Child("Ada",23);
c2.say(); //Ada,23,[red,blue]
c2.ps();  //Ada,[red,blue]

 

 


0 0
原创粉丝点击