---
title: "Ext 命名空间、类定义、继承、事件"
author: "alovejun14"
date: "2009-11-10T13:33:41Z"
tags: ["EXT", "prototype"]
slug: "ext"
draft: false
lastmod: "2009-11-10T13:35:08Z"
id: 513554
url: "https://alovejun14.iteye.com/blog/513554"
---

Ext.namespace("Ext.MyApp");      //定义命名空间。

        Ma = Ext.MyApp;    //定义命名别名。

        Ma.Person = Ext.emptyFn;        //Person类，人类在Ext.MyApp这个命名空间下。

        Ma.Student = Ext.emptyFn;       //Student 类。

        

        Ma.Person = function(\_cfg) {

            Ext.apply(this, \_cfg);         //\_cfg在实际中是如下格式{Name:'老狼',Sex:'男'}

        }

        Ma.Student = function(\_cfg) { //Student 类这里注册了一个名字改变时的事件。

            Ext.apply(this, \_cfg);

            this.addEvents('NameChange');     //注册事件。

        }

        Ext.extend(Ma.Person, Ext.util.Observable); //Person类继承Ext事件类。

        

        Ext.apply(Ma.Person.prototype, {  

        job:'无', //定义一个属性。

        print: function() { //定义一个方法。

            alert(String.format("姓名：{0} -- 性别：{1} --- 职业：{2}", this.Name, this.Sex));

            }

        });

 

        Ma.Person.Print = function(\_Name, \_Sex) {   //定义了一个Person类的静态方法。

            var Person = new Ma.Person({ Name: \_Name, Sex: \_Sex });

            Person.print();

        }

 

        

        Ext.extend(Ma.Student, Ma.Person, {   //Student类继承了Person类。

            job: '我是学生',     //重定义父类属性。

            setName: function(\_Name) {    //添加了一个新的方法用来设置名字。

                if (this.Name != \_Name) {

                    this.fireEvent('NameChange', this, this.Name, \_Name);     //触发事件的地方。

                    this.Name = \_Name;

                }

            },

            print: function() { //重写了父类Person的print方法。

                alert(String.format("姓名：{0} -- 性别：{1} --- 我的职业是：{2}", this.Name, this.Sex, this.job));  

            }

        });

       以下是调用的测试代码

        var st = new Ma.Student({ Name: '小花', Sex: '女' });   

        st.on("NameChange", function(sender, oldName, newName) {    //名字改变时的处理程序

            alert(String.format("原来的名字：{0} --- 新的名字：{1} --- 触发的对象:{2}", oldName, newName, sender));

        });

        st.setName("杰克老狼"); //设置名字

        st.print();                          //调用Student类的print函数。