javascript中的繼承

js中定義類或對象一般使用“構造函數+原型”方式:用構造函數定義所有非方法的成員,用原型定義方法成員

 js中的繼承有三種方法,對象冒充,原型鏈,對象冒充+原型鏈

/**  1、對象冒充   將Parent中執行的this綁定到對象child上
//寫法1
function Parent(){
    this.name="parent";
 this.sayName = function (){
   alert("I am "+this.name);
 }
}

 function Child(){
   
   this.name="child";
}

  var child = new Child();
  Parent.call(child);
  child.sayName(); 
//寫法2
function Parent(){
   this.name= "parent";
   this.sayName = function (){
        alert(" I am "+this.name);
   }
}
function Child (){
    this.age="26";
 Parent.call(this);
}
var child  = new Child();
child.sayName();
alert(child.name+"  "+child.age);

 

/** 2、 原型鏈  */
 function Parent (){
    this.name = "parent";
 this.age = "54";
 }

 function Child1 (){
    this.name = "child1"
    this.point = "北京";
 this.salary = "3500";
 }
Child1.prototype = new Parent();//
var child1 = new Child1();
alert(child1.name+"   "+child1.point+"  "+child1.salary);

function Child2(){
 this.point = "哈爾濱";
 this.salary = "5000";
}
Child2.prototype = new Parent();

var child2 = new Child2();
alert(child2.name+"  "+child2.point+"   "+child2.salary);

 /**  3、對象冒充+原型鏈 */

//實現繼承一般使用“對象冒充(object masquerading)+原型鏈”方式:用對象冒充繼承構造函數的所有成員,用原型鏈繼承原型的方法(用了原型鏈,instanceOf運算符纔有效)。

 Animal.prototype.ShowName =  function() {
     alert(this.name);
 }

 function Animal(animalName){
   this.name = animalName;
 
 }

 function Bird(birdName,birdColor){
     Animal.call(this,birdName);
  this.color = birdColor;
 }
 Bird.prototype = new Animal();
 Animal.prototype.age = "10";
 Bird.prototype.ShowColor = function (){
     alert(this.color);
 }

 var bird = new Bird("gugu","red");
 bird.ShowName();
 bird.ShowColor();
 alert(bird.age);

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章