js物件導向-繼承

來源:互聯網
上載者:User

標籤:blog   java   io   ar   div   cti   log   new   javascript   

定義父類
// 原型模式與建構函式組合function Person(name,age,job) {// 建構函式模式定義執行個體屬性this.name = name;this.age = age;this.job = job;}Person.prototype = {//原型模式定義方法和共用屬性constructor: Person,  //重寫原型改變了constructor,修正回來sayName:function() {alert(this.name);},sayJob:function() {alert(this.job);}}
  定義子類
// 定義Singer類,並指定job為singerfunction Singer(name,age,song) {Person.call(this,name,age,‘singer‘);this.song = song;}

  每次調用Singer建構函式都會把Singer的job設定為singer,並增加了一個屬性song。

Singer繼承Person
Singer.prototype = new Person();Singer.prototype.constructor = Singer;Singer.prototype.saySong = function() {alert(this.song);}

  第一步把Singer的原型設定為Person的執行個體對象,第二步修正constructor指向,因為Singer的prototype等於Person,所以它的constructor指向的Person函數,第三步添加了一個Singer對象的方法。

建立Singer對象
var TaylorSwift = new Singer(‘Taylor Swift‘,22,‘Love Story‘);TaylorSwift.saySong();  //"Love Story"TaylorSwift.sayJob();  //"singer"

  

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.