JavaScript實作類別,有多種方法。

來源:互聯網
上載者:User

方法一:構造方法。

  1. function coder(){
  2. this.name = '小王';
  3. this.job = '程式員';
  4. this.coding = function ()
  5. {
  6. alert('我正在寫代碼');
  7. }
  8. }
  9. var coder=new coder();
  10. alert(coder.name);
  11. coder.coding();

複製代碼

方法二:Factory 方法。

  1. function createCoderFactory(){
  2. var obj=new Object();
  3. obj.name = '小王';
  4. obj.job = '程式員';
  5. obj.coding = function (){
  6. alert('我正在寫代碼');
  7. };
  8. return obj;
  9. }
  10. var coder = createCoderFactory();
  11. alert(coder.name);
  12. coder.coding();

複製代碼

但Factory 方法和構造方法都有著一個相同的缺點,就是每建立一個執行個體,都會執行個體化該類的每個函數。

方法三:原形鏈。

  1. function coder(){}
  2. coder.prototype.name = '小王';
  3. coder.prototype.job = '程式員';
  4. coder.prototype.coding = function(){
  5. alert('我正在寫代碼');
  6. };
  7. var coder = new coder();
  8. alert(coder.name);
  9. coder.coding();

複製代碼

但原行鏈有個缺點就是它所有屬性都共用,只要一個執行個體改變其他的都會跟著改變。如:

  1. var coder1 = new coder();
  2. var coder2 = new coder();
  3. alert(coder1.name); /*顯示“小王”*/
  4. coder2.name = '老王';
  5. alert(coder1.name); /*示“老王”*/
  6. alert(coder2.name); /*這個也顯示“老王”*/

複製代碼

方法四:混合方式。

以上三種都有著各自的缺點,所以我們要加以改進。

  1. function coder(){
  2. this.name = '小王';
  3. this.job = '程式員';
  4. }
  5. coder.prototype.coding = function(){
  6. alert('我正在寫代碼');
  7. };

複製代碼

方法五:動態原鏈。

要解決前三種的缺點,還有一種方法。

  1. function coder(){
  2. this.name = '小王';
  3. this.job = '程式員';
  4. if (typeof(coder._init) == 'undefined'){
  5. this.coding = function ()
  6. {
  7. alert('我正在寫代碼');
  8. };
  9. this._init = true;
  10. }
  11. }
相關文章

聯繫我們

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