js繼承實現

來源:互聯網
上載者:User

標籤:

首先都知道js類是通過原型和構造器實現的,js中將類的方法放在function的prototype裡面了,它的每一個執行個體對象都可以獲得該類的方法,因此實現了繼承

    

 1 function Person(name,sex){ 2     this.name = name; 3     this.sex = sex; 4 } 5 Person.propotype.sayHello = function(){ 6     console.log(this.name + "say hello"); 7 } 8 function Female(age){ 9     this.age = age;10 };11 //Female也是Person,那麼Female怎麼去實現繼承呢?

 

實現繼承:

  Female.prototype == Person.prototype  //錯誤的實現

  這種方式只是簡單的將Femal的原型指向了Person的原型,即Female和Person指向同一個原型,當子類Female增刪改原型方法時,父類Person的原型也會被改變,所以該方法是不可取的。那麼應該怎麼做呢?

  就是讓Female的__proto__屬性指向Person的prototype對象,而不是直接把prototype指向Person的prototype。

  但是Femal.prototyoe.__proto__ = Person.prototype;  //也是不正確的

  因為__proto__不是一個標準的文法,在有些瀏覽器是擷取不到這個屬性的。

  那麼合理的做法應該是:讓Female的prototype指向一個obejct,這個object的__proto__指向Person的prototype

  大概實現如:

 

  那麼具體實現是:通過Object.create()複製一個新的prototype(該方法是在ES5中出現的,之前版本可以通過屬性遍曆實現淺拷貝)

    Female.prototype = Object.create(Person.prototype);

    console.log(girl instanceof Female); //false  這裡又為什麼是false?

  這裡就還包含了一個問題,就是constructor的指向不對,因為是clone過來的prototype,那麼prototype中的constructor還是指向Person(),那麼需要把   

    Femal.construtor = Femal; 這樣就徹底實現了繼承

  一般可以將該實現封裝成一個方法

  

1 function inherit(superType,subType){2     var _propotype = Object.create(superType.propotype);3     _propotype.construcotr = subType;4     _propotype.propotype = _propotype;5 }

那麼完整代碼:

  

 1 function Person(name,sex){ 2     this.name = name; 3     this.sex = sex; 4 } 5 Person.propotype.sayHello = function(){ 6     console.log(this.name + "say hello"); 7 } 8 function Female(name,sex,age){ 9     Person.call(this, name, sex);10     this.age = age;11 };12 //Female也是Person,那麼Female怎麼去實現繼承呢?13 // 在繼承函數之後寫自己的方法,否則會被覆蓋14 Female.prototype.printAge = function(){15     console.log(this.age);16 };17 var fm = new Female(‘Byron‘, ‘m‘, 26);18 fm.sayHello();

 

 

 

 

  

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.