实现vue中的$on $emit
var eventList = { 'sayName': [sayName] } var name = 'hehe' var age = 28 function sayName() { console.log(this.name) } function sayAge() { console.log(this.age) } function $on(type, fn) { if (!this.eventList[type]) { this.eventList[type] = [] } this.eventList[type].push(fn) } function $emit() { let type = Array.prototype.shift.call(arguments) let onCallbacks = eventList[type] onCallbacks.forEach(element => { element.apply(this, arguments) }); } $emit('sayName') // hehe $on('sayAge', sayAge) $emit('sayAge') // 28 $on('sayHello', (arg) => console.log(arg+ ', Hello!')) $emit('sayHello', 'John') // John, Hello!