溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

基于構(gòu)造函數(shù)的五種繼承方法小結(jié)

發(fā)布時(shí)間:2020-09-26 07:57:06 來源:腳本之家 閱讀:133 作者:jingxian 欄目:web開發(fā)

1.使用call或apply綁定構(gòu)造函數(shù)

  animal.apply(this.arguments)

2.使用prototype屬性  

  Cat.prototype = new Animal();

  Cat.prototype.constructor = Cat;

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

  alert(cat1.species); // 動(dòng)物

3.直接集成prototype屬性

  function Animal(){ }

  Animal.prototype.species = "動(dòng)物";

 

  Cat.prototype = Animal.prototype;

  Cat.prototype.constructor = Cat;

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

  alert(cat1.species); // 動(dòng)物

4.利用空對象作為中介

  var F = function(){};

  F.prototype = Animal.prototype;

  Cat.prototype = new F();

   Cat.prototype.constructor = Cat;

  將上面的方法封裝成一個(gè)函數(shù),便于使用:

    function extend(Child, Parent) {

      var F = function(){};

      F.prototype = Parent.prototype;

      Child.prototype = new F();

      Child.prototype.constructor = Child;

      Child.uber = Parent.prototype;

    }

5.拷貝繼承

function extend2(Child, Parent) {

    var p = Parent.prototype;

    var c = Child.prototype;

    for (var i in p) {

      c[i] = p[i];

      }

    c.uber = p;

  }

這個(gè)函數(shù)的作用,就是將父對象的prototype對象中的屬性,一一拷貝給Child對象的prototype對象。

以上這篇基于構(gòu)造函數(shù)的五種繼承方法小結(jié)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI