function Events(){ var obj = {}; this.on=function(key,fn){ var stack; stack = obj[key] || (obj[key] =[]); return stack.push(fn); } this.off=function(key){ var stack; return (stack=obj[key]) != null ? stack.length=0 : void 0;//此处stack.length=0不等同于stack=[],如果设置stack=[],并不能作用于object[key] } this.once=function(key,fn){ this.off(key); return this.on(key,fn); } this.trigger=function(){ var key,stack,i; key = [].shift.call(arguments); stack = obj[key]||(obj[key] = []); for(i=0;i<stack.length;i++){ stack[i].apply(this,arguments); } } } var events = new Events(); events.on("play",function(data){ console.log(data.name) }); events.on("play",function(data){ console.log(data.age) }); events.trigger("play",{name:"dpd",age:13})
时间: 2024-12-25 02:28:40