ExtJs4組件中initComponent方法介紹以及為什麼要使用this.callParent();

來源:互聯網
上載者:User

ExtJs4組件中initComponent方法介紹以及為什麼要使用this.callParent();
我們知道,Ext的UI組件有一個initCompent()方法。
這個方法定義在UI組件頂級類Component中,在Component的建構函式中會調用它進行組件初始化操作。
Component的子類都覆蓋了initCompent方法,在不同的層級上做了不同的處理。舉個例子,從Window一直

到Conponent,會形成這樣一個調用鏈條。

 

可以看到初始化當前組件的時候,要從最頂端組件開始初始化,每個組件都承擔了構建最終組件的任務。

 

看到這裡我們不禁發出疑問,怎麼在調用當前組件的initComponent方法前還去調用下父類的呢?

 

學過java的同學都知道,java如果想在當前方法調用父類的同名方法,可以super.方法名();

首先介紹下Ext3是怎麼處理的

 

MyClass1 = function(){}MyClass1.prototype={say:function(){console.log('hello1');}}MyClass2 = Ext.extend(MyClass1,{say:function(){MyClass2.superclass.say.call(this);console.log('hello2');}});//每次子類需要調用超類方法,都要像下面這樣寫:MyClass2.superclass.say.call(this);

這種寫法有幾個弊端:
類名要內建到函數代碼模組中,如果一旦修改類名,就非常麻煩每次的調用都要寫一長串代碼,有時候為了省事複製粘貼,忘記改類名,就會出錯有時候需要傳參,使用call與apply調用用法不統一

 

如何做到像java那樣呢

 

public MyClass2 extends MyClass1{      public void say() {          super.say();          System.out.println('MyClass2 say hello world!');      }  } 
ExtJs4就完美解決了

 

 

Ext.define('MyClass1',{say: function(){console.log('hello1');}})Ext.define('MyClass2',{extend:'MyClass1',    say: function(){          this.callParent(); // 調用父類的say()          // 如果要為父類方法傳參,只需要像下面這樣寫          //this.callParent(arguments);          //this.callParent([param1, param2]);          console.log('hello2');    }  });Ext.define('MyClass3',{extend:'MyClass2',    say: function(){          this.callParent(); // 調用父類的say()          // 如果要為父類方法傳參,只需要像下面這樣寫          //this.callParent(arguments);          //this.callParent([param1, param2]);          console.log('hello3');    }  });

 

聯繫我們

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