// 简单的订阅-发布模式,没有验证
//
//
// 注意!!! on 和 emit 方法的定义必须使用function,不能使用箭头函数,因为箭头函数的this特性
function Scope(name) {
this.name = name
this.events = {
'default' : () => {
console.log('default event')
}
}
}
Scope.prototype.on = function(evtName, cb){
this.events[evtName] = () => {
cb && cb()
}
console.log(this.events, 'from on')
}
Scope.prototype.emit = function(evtName) {
console.log(this.events, 'from emit')
this.events[evtName] && this.events[evtName]()
}
var people = new Scope('小明')
console.log(people)
people.on('eat', () => {
console.log(this.name , 'I am eating')
})
people.emit('default')
people.emit('eat')
转载于:https://my.oschina.net/boogoogle/blog/1524351