---
title: "ExtJs 4 类的定义方式改进"
author: "jiming"
date: "2011-11-13T08:27:11Z"
tags: []
categories: ["Web前端"]
slug: "extjs-4"
draft: false
lastmod: "2011-11-13T08:27:33Z"
id: 1255183
url: "https://jiming.iteye.com/blog/1255183"
---

Extjs 3 中是这样定义类的：

 

```
MyApp.LoginWindow = Ext.extend(Ext.Window, {
    title: 'Log in',
 
    initComponent: function() {
        Ext.apply(this, {
            items: [
                {
                    xtype: 'textfield',
                    name : 'username',
                    fieldLabel: 'Username'
                },
                ...
            ]
        });
 
        MyApp.LoginWindow.superclass.initComponent.apply(this, arguments);
    }
});
```

 Extjs4 中改成：

 

 

 

```
Ext.define('MyApp.LoginWindow', {
    extend: 'Ext.Window',
 
    title: 'Log in',
 
    initComponent: function() {
        Ext.apply(this, {
            items: [
                //as above
            ]
        });
 
        MyApp.LoginWindow.superclass.initComponent.apply(this, arguments);
    }
});
 
```

 这样做有两个好处：

 

- 不会出现忘记定出 MyApp namespace 的情况
- 如果 Ext.Window 的定义位置比 MyApp.LoginWindow 晚，使用 4 的方式可以延时定义 LoginWindow 知道找到了 Ext.Window 的定义