ExtJS 提供了完整的類系統,支援命名空間、類定義、繼承、混入、靜態成員、單例等企業級開發特性,讓 JavaScript 具備類 Java/C# 的結構化組織能力,極大提升大型應用的可維護性。
// 定義命名空間
Ext.namespace('Ext.wentao');
// 定義類(相當於 constructor function)
Ext.wentao.helloworld = Ext.emptyFn; // 等價於 function(){}
// 實例化
new Ext.wentao.helloworld();
Ext.wentao.Person = Ext.emptyFn;
Ext.apply(Ext.wentao.Person.prototype, {
name: '劉文濤',
sex: '男',
print: function() {
alert(Ext.String.format('姓名:{0}, 性別:{1}', this.name, this.sex));
}
});
var person = new Ext.wentao.Person();
person.print(); // 調用實例方法
person.name = '張三'; // 修改實例屬性
Ext.wentao.Person.print = function(_name, _sex) {
var p = new Ext.wentao.Person();
p.name = _name; p.sex = _sex;
p.print(); // 內部調用實例方法
};
Ext.wentao.Person.print('張三', '女'); // 直接通過類名調用
Ext.wentao.Person = function(cfg) {
Ext.apply(this, cfg); // 將配置對象屬性混入實例
};
Ext.apply(Ext.wentao.Person.prototype, {
print: function() { /* ... */ }
});
// 使用配置對象實例化
new Ext.wentao.Person({ name: '李四', sex: '女' });
// 父類
Ext.wentao.Person = function(cfg) { Ext.apply(this, cfg); };
Ext.apply(Ext.wentao.Person.prototype, {
job: '無',
print: function() { alert('姓名:' + this.name + ', 角色:' + this.job); }
});
// 子類
Ext.wentao.Student = function(cfg) { Ext.apply(this, cfg); };
Ext.extend(Ext.wentao.Student, Ext.wentao.Person, {
job: '學生', // 覆寫屬性
// print: function() { ... } // 可選:覆寫方法
});
var student = new Ext.wentao.Student({ name: '張三', sex: '女' });
student.print(); // 輸出:姓名:張三, 角色:學生
Ext.extend(Ext.wentao.Student, Ext.wentao.Person, {
job: '學生',
print: function() {
// 調用父類方法:Ext.wentao.Student.superclass.print.call(this)
// 或使用 Ext.apply 覆寫後手動調用
alert(this.name + '是一位' + this.sex + this.job);
}
});
// 命名空間別名
var Wt = Ext.wentao;
// 類別名
var PN = Wt.Person;
var ST = Wt.Student;
Ext.extend(ST, PN, { job: '學生', print: function(){ /*...*/ } });
new ST({ name: '王五', sex: '男' }).print();
ExtJS 4+ 引入新類系統,強烈建議使用新語法:
Ext.define('Ext.wentao.Person', {
config: { name: '', sex: '', job: '無' },
constructor: function(cfg) { this.initConfig(cfg); },
print: function() { /* ... */ }
});
Ext.define('Ext.wentao.Student', {
extend: 'Ext.wentao.Person',
config: { job: '學生' },
print: function() {
this.callParent(); // 調用父類方法
// 或完全重寫
}
});
var student = Ext.create('Ext.wentao.Student', { name: '趙六', sex: '男' });
掌握 ExtJS 類系統的關鍵點:
Ext.namespace 組織代碼結構prototype 承載實例成員,構造函數承載靜態成員Ext.extend(child, parent, overrides) 實現繼承Ext.define、Ext.create、callParent 現代 API