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'); } });