定义对象时,initComponent与constructor有什么区别?

20

相对于constructor,我应该在什么时候使用initComponent

我一直在使用initComponent来扩展我的对象,但是看着Ext.define的文档,我发现他们到处都在使用constructor。有什么区别吗?

比较:

Ext.define('My.app.PanelPart2', {
    extend: 'My.app.Panel',
    constructor: function (config) {
        this.callSuper(arguments); // calls My.app.Panel's constructor
        //...
    }
});
Ext.define('My.app.PanelPart2', {
    extend: 'My.app.Panel',
    initComponent: function (config) {
        Ext.apply(this, config);
        this.callParent(arguments);
    }
});
我知道有些组件不会初始化(我在看你,Ext.data.Store),这使我倾向于只覆盖构造函数,因为那应该是通用的。
1个回答

36

constructor是面向对象编程中用于初始化对象实例的标准,它在每个ExtJS类中都可用(由Ext.define创建的所有类)。

initComponent是ExtJS的扩展,用于初始化组件 - 即扩展了Ext.Component的类。它使用模板方法模式,并在自定义组件初始化之前和之后启用一些标准初始化步骤。大概像这样:

Ext.Component.constructor() {
    - init events
    - apply config
    - create plugins
    - ...
    - your custom component initialization (initComponent)
    - ...
    - init plugins
    - etc.
}

我的最佳实践是在创建自定义组件时使用initComponent,而只在通用类中使用constructor


你好,这个定义现在仍然适用吗?请使用Extjs的版本3。它的定义仍然可以使用吗?您能否为我提供一些关于InitComponent的学习链接?非常感谢您的帮助。 - durtto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接