initComponent是在construor里被调用,constructor是在其他地方调用;一个用于具体的创建控件,一个是用于创建控件对象在创建自定义类时,先构造(constructor)后初始化(initComponent)。如: Ext.define('Btn',{ extend:'Ext.button.Button', initComponent:function(){ alert('后初始化部件启动...'); }, constructor:function(){ this.text = new Date(); this.renderTo = Ext.getBody(); this.callParent(); alert('先构造函数启动...'); } }); Ext.onReady(function(){ Ext.create('Btn'); });
initComponent这个方法是在Ext.Component的构造函数(constructor)中调用的,只有直接或间接继承自 Ext.Component的类才会在constructor里调用initComponent方法。
我们知道,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);这种写法有几个弊端:
如何做到像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'); } });