定义对象时的initComponent与构造函数

时间:2011-10-04 18:06:38

标签: extjs4 extjs

initComponent相比,我应该何时使用constructor

我一直在使用initComponent来扩展我的对象,但查看Ext.define的文档是使用构造函数查看它们然后放置。有什么区别?

比较

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 个答案:

答案 0 :(得分:36)

constructor是初始化对象实例的OOP标准,并且在每个ExtJS类(Ext.define创建的所有内容)中都可用。

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

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

我最好的做法是每当我创建自定义组件时使用initComponent,而仅为通用类使用constructor

相关问题