<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var Event = {
// 通过on接口监听事件eventName
// 如果事件eventName被触发,则执行callback回调函数
on: function(eventName, callback) {
//你的代码 注册事件
/*if(!this.obj){
this.obj={};
} *///只满足测试1的要求
if(!this.obj){
Object.defineProperty(this,"obj",{
enumerable:false,
value:{}
});
}
if(!this.obj[eventName]){
this.obj[eventName] = [callback];
}
else{
this.obj[eventName].push(callback);
}
},
// 触发事件 eventName
emit: function(eventName) {
//你的代码 发布事件
if(this.obj[eventName]){
for(var i=0; i<this.obj[eventName].length; i++){
this.obj[eventName][i](arguments[1]);
}
}
}
};
// 测试1
Event.on('test', function(result) {
console.log(result);
});
Event.on('test', function() {
console.log('test');
});
Event.emit('test', 'hello world'); // 输出 'hello world' 和 'test'
// 测试2
var person1 = {};
var person2 = {};
Object.assign(person1, Event);
Object.assign(person2, Event);
person1.on('call1', function() {
console.log('person1');
});
person2.on('call2', function() {
console.log('person2');
});
person1.emit('call1'); // 输出 'person1'
person1.emit('call2'); // 没有输出
person2.emit('call1'); // 没有输出
person2.emit('call2'); // 输出 'person2'
</script>
</body>
</html>
有关设计模式的面试题
最新推荐文章于 2024-03-20 04:52:47 发布