1 var Event = { 2 on: function (eventName, callback) { 3 console.log("eventName:"+eventName) 4 if (!this.handles) { 5 Object.defineProperty(this, "handles", { 6 value: {}, 7 enumerable: false//不可枚举 8 }) 9 //this.handles = {};//可以枚举 10 } 11 if (!this.handles[eventName]) { 12 this.handles[eventName] = []; 13 } 14 this.handles[eventName].push(callback); 15 }, 16 emit: function () { 17 var hlist = this.handles[arguments[0]] || []; 18 for (var i = 0; i < hlist.length; i++) { 19 this.handles[arguments[0]][i](arguments[1]); 20 } 21 } 22 } 23 Event.on("dome", function (params) { 24 console.log(params); 25 }); 26 Event.on("dome", function (params) { 27 console.log("dome log"); 28 }); 29 Event.emit("dome", "holle world"); 30 31 var person1 = {}; 32 var person2 = {}; 33 //Object.assign是浅复制,会导致person1,person2共用同一个handles 34 Object.assign(person1, Event); 35 Object.assign(person2, Event); 36 person1.on('call1', function () { 37 console.log('person1'); 38 }); 39 person2.on('call2', function () { 40 console.log('person2'); 41 }); 42 person1.emit('call1'); // 输出 'person1' 43 person1.emit('call2'); // 没有输出 44 person2.emit('call1'); // 没有输出 45 person2.emit('call2'); // 输出 'person2'