<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>
// 定义一个猫的类
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>