用js实现猫与老鼠的事件编程

<script type="text/javascript">
// 定义一个猫的类
function Cat(description) {
    // 定义一个事件
    this.description = description;
    this.cry = null;
}
// 添加事件
Cat.prototype.AddHandler = function(handler) {
    if (this.cry == null) {
        this.cry = new Array();
        this.cry[this.cry.length] = handler;
   } else {
       this.cry[this.cry.length] = handler;
   }
}
// 定义猫叫的方法
Cat.prototype.OnCry = function() {
    alert("Cat:miao miao.");
   for (var i = 0;i < this.cry.length; i++) {
        this.cry[i](this);
    }
}
// 定义一个老鼠类,老鼠对猫的叫感兴趣,所以就注册了cry事件
function Mouse() {
}
Mouse.prototype.Run = function(des) {
   switch (des.description) {
        case "laze" :
           alert("Mouse: Laze I'm not fraid!");
           break;
       case "smark" :
           alert("Mouse:I must run!");
            break;
   }
}
var c = new Cat('laze');
var c2 = new Cat('smark');
var m = new Mouse();
c.AddHandler(m.Run);
c2.AddHandler(m.Run);
// 先让懒猫先叫
c.OnCry();
// 再让NB的猫再叫
c2.OnCry();
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值