js的建構函式繼承的幾種類型

來源:互聯網
上載者:User

標籤:將不   需要   console   this   animal   tor   資料   arguments   構造   

function animale(){

         this.species ="貓科";

}

function cat(){

       this.name=name;  

       this.color=color

}

1:基於apply()方法和call()方法

在子項目中加入一行代碼

function cat(){

      this.name=name;

      this.color=color;

      animale.apply(this,arguments);  //這裡的this就是指當前調用對象

}

var cat1=new cat("大黃","白色");

var cat2=new cat("戈薇","灰色");

console.log(cat1.species);

console.log(cat2.species);

缺點:不能調用父類原型類中的方法和屬性

eg:animale.prototype.show=function(){alert(this.color)}

cat1.show();>-----undefined

2:基於原型的繼承

cat.prototype=new animale();  //定義玩這句後cat.prototype.constructor就指向了animale

cat.prototype.constructor=cat;

var cat3 =new cat("大黃","白色");

var cat2=new cat("戈薇","灰色");

console.log(cat2.species);

//可以訪問animale原型中的方法和屬性,但是不能直接存取父類的建構函式,第一代改變了父類的參考型別的值,其他的子代也會改變,但基本類型的值不會隨著改變。

eg:cat3.species="犬科";

console.log(cat2.species);   >-----貓科

3:利用空媒介進行封裝處理(基於直接用原型繼承的改變)

我們將不需要變化的資料放到父類 的原型裡面

animale.prototype.species="貓科"

function f(){}   //空函數,F是Null 物件,所以幾乎不佔記憶體

f.prototype=animale.prototype; 

cat.prototype = new f();

cat.prototype.constructor =cat;

我們在把上述代碼通過一個函數進行封裝

function excent(child,parent){

     var F=function(){}

     F.prototype=parent.prototype;

     child.prototype=new F();

     child.prototype.constructor=child;

}

excent(cat,animale);

var cat1 = new Cat("大毛","黃色");

  alert(cat1.species); // 動物

js的建構函式繼承的幾種類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.