您的位置:首页 > Web前端 > JavaScript

[Ext JS 4] Extjs 之 initComponent 和 constructor的区别

2015-11-11 11:26 591 查看


[Ext JS 4] Extjs 之 initComponent 和 constructor的区别

分类: Web-编程语言2014-07-02
08:33 5244人阅读 评论(0) 收藏 举报

目录(?)[+]


initComponent 和 constructor是什么

Extjs 提供的组件还是挺丰富的, 但是有时候需求更丰富。

当Extjs 原生的组件无法实现我们的要求的时候, 就需要扩展Extjs 的组件实现自制组件了。

除了这种使用状况, 有时候对于一些相同却有使用很多的配置, 可能像把它独立出来,单独设为一种组件供大家调用, 节省开发时间和提高代码重用度。

initComponent 和 constructor 就是Extjs 提供用来实现继承和扩展的方式。


Ext.define 实现扩展

在Extjs 中使用Ext.define来实现扩展, initComponent 和 constructor的使用方式类似

[html] view
plaincopy

Ext.define('Ext.oscar999.button.MyButton', {  

    extend : 'Ext.button.Button',  

    initComponent : function() {  

        //do something  

    },  

    constructor : function() {  

        //do something  

    }  

});  

一般状况上,加上 xtype 的定义, 类似:

(在旧的Extjs 版本中使用 Ext.extend 实现扩展)

那么这两种用法究竟该如何使用? 两者的使用又有什么差别呢?



initComponent 和 constructor区别于联系

1. initComponent这个方法是在Ext.Component的构造函数(constructor)中调用的,只有直接或间接继承自 Ext.Component的类才会在constructor里调用initComponent方法

看一下  Ext.AbstractComponent的源码文件 src/AbstractComponent.js

在  constructor方法中调用了initComponent

2. 

   1)自定义类中的 initComponent 函数中必须调用 callParent();否则 调用者无法初始化这个对象

   2)针对button 这样的扩展组件来说,自定义类中的  constructor ,需要调用callParent( arguments);否则 调用者无法初始化这个对象

[html] view
plaincopy

this.callParent(arguments);  

这里的arguments 是需要的。

(在Extjs 4 之前的版本中, 可能会看到比较多的XXX.superclass.constructor.call 写法)

sencha 的官网中有一篇针对这两个区别的讨论:

http://www.sencha.com/forum/showthread.php?47210-constructor-Vs-initComponent

不过语法是基于Extjs 3 来讨论的, 笔者觉得作用不是很大。

就笔者实际的开发经验来看, 基本上使用initComponent 就可以达到开发的要求了。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: