Ext提供了这样的一个实用函数 Ext.extend (API 参考) 在EXT框架中实现类继承的机制。这赋予了你扩展任何JavaScript基类的能力,而无须对类自身进行代码的修改(这里通常指的是子类,或是从它继承的,一个基类)扩展Ext组件这是个较理想的方法。
要从一个现有的类创建出一个新类,首先要通过一个函数声明新类的构造器,然后调用新类属性所共享的扩展方法。这些共享的属性通常是方法,但是如果要在实例之间共享数据(例如,Java中的静态类变量),应该也一同声明。
JavsScript并没有提供一个自动的调用父类构造器的机制,所以你必须通过属性superclass在你的构造器中显式调用父类。第一个参数总是this,以保证构造器工作在调用函数的作用域。
?
- MyNewClass?=?function(arg1,?arg2,?etc)?{ ??
- ???//?显式调用父类的构造函数 ??
- ???MyNewClass.superclass.constructor.call(this,?arg1,?arg2,?etc);? ??
- }; ??
- ? ??
- Ext.extend(MyNewClass,?SomeBaseClass,?{ ??
- ??theDocument:?Ext.get(document), ??
- ??myNewFn1:?function()?{ ??
- ????//?etc. ??
- ??}, ??
- ??myNewFn2:?function()?{ ??
- ???//?etc. ??
- ??} ??
- });??
MyNewClass = function(arg1, arg2, etc) { // 显式调用父类的构造函数 MyNewClass.superclass.constructor.call(this, arg1, arg2, etc); }; Ext.extend(MyNewClass, SomeBaseClass, { theDocument: Ext.get(document), myNewFn1: function() { // etc. }, myNewFn2: function() { // etc. } });
?
?下面的一个例子是Ext的实际案例,用于可缩放,拖动元素,X、Y的坐标值指定了对象可在垂直、水平方向拖动的距离。
?
- //?创建新类的构造函数 ??
- Ext.ResizableConstrained?=?function(el,?config){ ??
- ????Ext.ResizableConstrained.superclass.constructor.call(this,?el,?config); ??
- }; ??
- ? ??
- //?扩展基类 ??
- Ext.extend(Ext.ResizableConstrained,?Ext.Resizable,?{ ??
- ????setXConstraint?:?function(left,?right){ ??
- ????????//?得到父类的属性dd和setXConstraint的引用 ??
- ????????this.dd.setXConstraint(left,?right); ??
- ????}, ??
- ? ??
- ???setYConstraint?:?function(up,?down){ ??
- ?????//?得到父类的属性dd和setYConstraint的引用 ??
- ?????this.dd.setYConstraint(up,?down); ??
- ???} ??
- }); ??
- ? ??
- //?创建新类的实例 ??
- var?myResizable?=?new?Ext.ResizableConstrained('resize-el',?{ ??
- ???width:?200, ??
- ???height:?75, ??
- ???minWidth:100, ??
- ???minHeight:50,? ??
- ???maxHeight:150,? ??
- ???draggable:true??
- }); ??
- ? ??
- //调用新方法 ??
- myResizable.setYConstraint(0,300); ??
- myResizable.setXConstraint(0,300);??
?
from Ext继承关系 讲解