『ExtJS』01 002. ExtJS 4 类的继承

介绍在ExtJS 4中类的继承。

几点说明


  1. 这边文章主要讲解如何去扩展一个已经存在的类,以及使用新的方法重载父类的方法。
  2. 我们将定义一个简单的类Vehicle,在其中有Manufacturer、Model、Top speed三个属性,一个travel方法。

代码


ExtJS:4.0.7

IDE:Eclipse Java EE

浏览器:Chrome 25

   1: //-------父类--------------------------------------
   2:  
   3: Ext.define('Cookbook.Vehicle', {
   4:     config : {
   5:         manufacturer : 'Unknown Manufacturer',
   6:         model : 'Unknown Model',
   7:         topSpeed : 0
   8:     },
   9:  
  10:     constructor : function(manufacturer, model, topSpeed) {
  11:         // initialise our config object
  12:         this.initConfig();
  13:  
  14:         if (manufacturer) {
  15:             this.setManufacturer(manufacturer);
  16:         }
  17:         if (model) {
  18:             this.setModel(model);
  19:         }
  20:         if (topSpeed) {
  21:             this.setTopSpeed(topSpeed);
  22:         }
  23:     },
  24:  
  25:     travel : function(distance) {
  26:         alert('The ' + this.getManufacturer() + ' ' + this.getModel()
  27:                 + ' travelled ' + distance + ' miles at ' + this.getTopSpeed()
  28:                 + 'mph');
  29:     }
  30: }, function() {
  31:     console.log('Vehicle Class defined!');
  32: });
  33:  
  34: //-------调用父类------------------------------------
  35:  
  36: var vehicle = Ext.create('Cookbook.Vehicle', 'Aston Martin', 'Vanquish', 60);
  37: vehicle.travel(100);
  38:  
  39: //-------子类--------------------------------------
  40:  
  41: Ext.define('Cookbook.Plane', {
  42:     extend : 'Cookbook.Vehicle',
  43:  
  44:     config : {
  45:         maxAltitude : 0
  46:     },
  47:  
  48:     constructor : function(manufacturer, model, topSpeed, maxAltitude) {
  49:         // intialise our config object
  50:         this.initConfig();
  51:  
  52:         if (maxAltitude) {
  53:             this.setMaxAltitude(maxAltitude);
  54:         }
  55:  
  56:         // call the parent class' constructor
  57:         this.callParent([ manufacturer, model, topSpeed ]);
  58:     }
  59: }, function() {
  60:     console.log('Plane Class Defined!');
  61: });
  62:  
  63: //-------实例化并调用----------------------------------
  64:  
  65: var plane = Ext.create('Cookbook.Plane','Boeing','747',500,30000);
  66: plane.travel(800);

说明


  1. extend配置选项告诉Ext.Class扩展预处理器你的新类继承自哪里。预处理器会合并所有父类的成员到新的类中,达到扩展类的目的。
  2. callParent方法是一种执行父类方法的途径。
  3. 我们可以使用与父类方法名称相同,但参数不同的方法来对父类的方法进行重载。
  4. 类的继承示意图:

image

总结


总的来说,ExtJS关于类的继承,在概念上于一般的继承相同。不同的就是这种代码的书写格式需要记忆与注意。(PS:特别是符号千万不要漏了!)






版权声明:

作者:莫不逢
出处:http://www.cnblogs.com/sitemanager/
Github:https://github.com/congjf

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


原文地址:https://www.cnblogs.com/sitemanager/p/2785003.html