原文地址:EXTJS中的类和继承
作者:沧海一笑
Extjs 继承的使用
首先看一下经典的JavaScript的继承机制。
定义一个名为BaseClass的类,然后为BaseClass定义两个函数:someMethod()和overridenMethod().
var
BaseClass
=
function
(){
// do something
};
BaseClass.prototype.someMethod
=
function
(){
// do something
};
BaseClass.prototype.overridenMethod
=
function
(){
// do something
};
// do
};
BaseClass.prototype.someMethod
// do
};
BaseClass.prototype.overridenMethod
// do
};
谈到类和继承, 有几个函数必须注意, Ext.apply、 Ext.applyIf和Ext.extend:
- Ext.apply(obj, config, [defaults]) 将config对象的所有属性都复制到另一个对象obj上,第三个参数defaults可以用来提供默认值,不过通常指用前两个参数就够了。这个函数主要用在构造函数中, 用来将配置复制到对象上。
- Ext.applyIf(obj, config) 和Ext.apply的功能类似,唯一不同的是,这个函数只会将config对象中有,而obj对象中没有的属性复制到obj上。
- Ext.extend(subclass, superclass, [overrides]) 用来继承已有的类, 通常的使用方法有
使用传统方式在JavaScript中实现类的继承操作:
var在ExtJS中使用Ext.extend()函数实现继承功能:SubClass = function (){
BaseClass.call( this );
};
SubClass.prototype= new BaseClass();
SubClass.prototype.newMethod = function (){
// do something
};
SubClass.prototype.overridenMethod= function (){
// do something
};var SubClass = function() {
SubClass.superclass.constructor.call(this);
};
Ext.extend(SubClass, BaseClass, {
newMethod : function() {},
overriddenMethod : function() {}
};
Extjs中替换constructor,写法如下:
//initComponent replaces the constructor:
SubClass =Ext.extend(BaseClass, {
initComponent : function(){
// call superclass initComponent
Ext.Container.superclass.initComponent.call(this);
this.addEvents({
// add events
});
}
}
Ext.extend()函数提供了直接访问父类构造函数的途径,通过 SubClass.superclass.constructor.call(this);就可以直接调用父类的构造函数,这个函数的第一个参数总是 this,以确保父类的构造函数在子类的作用域里工作。
如果父类的构造函数需要传入参数,可以讲所需的参数直接传递给它:
SubClass.superclass.constructor.call(this,config);这样就得到了一个继承了父类的所有属性和函数的子类。Ext.apply函数的作用是将一个对象中的所有属性都复制到另一个对象中。
Ext.applyIf与Ext.apply的作用类似,区别在于如果某个属性在目标对象中已经存在,则Ext.applyIf不会将它覆盖。
在上面的代码中, SubClass继承自BaseClass, 添加了新的方法newMethod, 重写了overriddenMethod方法。