javascript實現繼承的三種方式

來源:互聯網
上載者:User

標籤:AC   prototype   var   輸出   cal   asc   class   實現繼承   parent   

一、原型鏈繼承 

 

function Parent(){} function Child(){} Child.prototype = new Parent(); 

通過對象child的prototype屬性指向父物件parent的執行個體,使child對象的執行個體通過原型鏈訪問到父物件構造所定義的屬性、方法等。

二、使用apply、call方法 

js中call和apply都可以實現繼承,唯一的一點參數不同,func.call(func1,var1,var2,var3)對應的apply寫法為:func.apply(func1,[var1,var2,var3])。

相同點:第一個參數this都一樣,指當前對象。

不同點,第二參數不一樣,call是一個個的參數列表,apply是一個數組(arguments也可以)

<script type="text/javascript">      function  Person(name,age,love){          this.name=name;          this.age=age;          this.love=love;          this.say=function say(){              alert("姓名:"+name);          }      }      //call方式      function student(name,age){          Person.call(this,name,age);      }      //apply方式      function teacher(name,love){          Person.apply(this,[name,love]);          //Person.apply(this,arguments); //跟上句一樣的效果,arguments      }      //call與aplly的異同:      //1,第一個參數this都一樣,指當前對象      //2,第二個參數不一樣:call的是一個個的參數列表;apply的是一個數組(arguments也可以)      var per=new Person("武鳳樓",25,"魏熒屏"); //輸出:“武鳳樓”      per.say();      var stu=new student("曹玉",18);//輸出:“曹玉”      stu.say();      var tea=new teacher("秦傑",16);//輸出:“秦傑”      tea.say();  </script>  

 

 

三、對象執行個體間的繼承 

 

 

 

 

原文來自:http://www.jb51.net/article/20431.htm

 

javascript實現繼承的三種方式

相關文章

聯繫我們

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