1// 定义一个猫的类
 2function Cat(description) {
 3    // 定义一个事件
 4    this.description = description;
 5    this.cry = null;
 6}

 7// 添加事件
 8Cat.prototype.AddHandler = function(handler) {
 9    if (this.cry == null{
10        this.cry = new Array();
11        this.cry[this.cry.length] = handler;
12    }
 else {
13        this.cry[this.cry.length] = handler;
14    }

15}

16// 定义猫叫的方法
17Cat.prototype.OnCry = function() {
18    alert("Cat:miao miao.");
19    for (var i = 0;i < this.cry.length; i++{
20        this.cry[i](this);
21    }

22}

23// 定义一个老鼠类,老鼠对猫的叫感兴趣,所以就注册了cry事件
24function Mouse() {
25}

26Mouse.prototype.Run = function(des) {
27    switch (des.description) {
28        case "laze" :
29            alert("操,你吓我是吧,你能追的上我吗,我就不跑!");
30            break;
31        case "smark" :
32            alert("我日,你来了呀,你NB,我走!");
33            break;
34    }

35}

36var c = new Cat('laze');
37var c2 = new Cat('smark');
38var m = new Mouse();
39c.AddHandler(m.Run);
40c2.AddHandler(m.Run);
41// 先让懒猫先叫
42c.OnCry();
43// 再让NB的猫再叫
44c2.OnCry();
posted on 2008-07-18 16:10  *海风*  阅读(371)  评论(0编辑  收藏  举报