淺談Javascript實現繼承的方法_javascript技巧

來源:互聯網
上載者:User

S1:js中一切皆對象,想想如果要實現對父物件屬性和方法的繼承,最初我們會怎樣子來實現呢,考慮到原型的概念,最初我是這樣來實現繼承的

function Parent(){   this.name='123';}Parent.prototype.getName=function(){   return this.name;}function Son(){   this.age=20;}Son.prototype=new Parent();Son.prototype.getAge=function(){   return this.age;}var son=new Son();console.log('Name :'+son.getName()+';Age: '+son.getAge());  VM1777:16 Name :123;Age: 20

從上面可以看到實現對Parent的繼承主要是覆寫了Son的prototype,這樣便把Parent的屬性和方法過給了Son的原型,這樣子在通過new Son()構造出來的對象均會繼承來自原型【即父物件Parent】的屬性和方法,這樣就達到了繼承效果;但這樣會帶來一個副作用,就是當父物件中包含參考型別的屬性時,子物件對參考型別資料的修改,會影響到所有的子物件,顯然這不是我們需要的效果:

function Parent(){   this.name='123';   this.fruits=['apple'];}Parent.prototype.getName=function(){   return this.name;}function Son(){   this.age=20;}Son.prototype=new Parent();Son.prototype.getAge=function(){   return this.age;}var son=new Son();var son1=new Son();console.log(son.fruits);//["apple"]console.log(son1.fruits);//["apple"]son.fruits.push('pear');console.log(son.fruits);//["apple", "pear"]console.log(son1.fruits);//["apple", "pear"]

S2:目前想到要解決這個問題就是使每個子物件都擁有一份父物件屬性的複製品,這樣修改屬性時只是修改了子物件下的屬性,而不會影響到其他的子物件屬性。這一目標的實現參照前人的對象冒充的方式來實現

function Parent(){   this.name='123';   this.fruits=['apple'];}Parent.prototype.getName=function(){   return this.name;}function Son(){   Parent.call(this);   this.age=20;}Son.prototype=new Parent();Son.prototype.getAge=function(){   return this.age;}var son=new Son();var son1=new Son();console.log(son.fruits);//["apple"]console.log(son1.fruits);//["apple"]son.fruits.push('pear');console.log(son.fruits);//["apple", "pear"]console.log(son1.fruits);//["apple"]

上面我在Son函數裡加了Parent.call(this)實現在new Son()的時候將this[即new 出來的Son對象]冒充成Parent函數裡的上下文this來調用Parent()函數,從而拿到了父物件的屬性和方法副本,所以在接下來修改父物件的屬性和方法時其實是修改的副本,故達到了不會影響全部子物件的效果。但是由於Son.prototype=new Parent()的使用,我們得到了兩份執行個體的屬性和方法,而再我們拿到了副本以後,只是需要父物件的原型就行了,從下面可以看出我們只需要原型中的getname();

S3:接下來就是要去掉一份執行個體的屬性和方法,這時候是constructor發揮作用的時候了,看下邊代碼,將Parent.prototype重新構建成一個原生對象,來作為子物件的原型,再把constructor指向子構造器

function Parent(){   this.name='123';   this.fruits=['apple'];}Parent.prototype.getName=function(){   return this.name;}function Son(){   Parent.call(this);   this.age=20;}function Extend(Parent,Son){   var proto = new Object(Parent.prototype);   proto.constructor = Son;   Son.prototype=proto;}Extend(Parent,Son);Son.prototype.getAge=function(){   return this.age;}

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.