盒子
盒子

解答一下问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class People {
constructor(name) {
this.name = name;
this.fnList = [];
}

// TODO: 请在此处完善代码
on(type, fn) {
if(!Array.isArray(this.fnList[type])) {
this.fnList[type] = [];
}
this.fnList[type].push(fn);
}

emit(type) {
if(Array.isArray(this.fnList[type]) && this.fnList[type].length > 0) {
this.fnList[type].forEach((fn) => {
fn.apply(null, [].slice.call(arguments, 1));
})
}
}

off(type, fn) {
this.fnList[type] = Array.isArray(this.fnList[type]) ? this.fnList[type] : [];
this.fnList[type].forEach((item, i) => {
if(item === fn) {
this.fnList[type].splice(i, 1);
}
})
}

sayHi() {
console.log(`Hi, I am ${this.name}`)
}
}


/* 以下为测试代码 */
const say1 = (greeting) => {
console.log(`${greeting}, nice meeting you.`)
}

const say2 = (greeting) => {
console.log(`${greeting}, nice meeting you, too.`)
}

const jerry = new People('Jerry')
jerry.sayHi()
// => 输出:'Hi, I am Jerry'

jerry.on('greeting', say1)
jerry.on('greeting', say2)

jerry.emit('greeting', 'Hi')
// => 输出:'Hi, nice meeting you.' 和 'Hi, nice meeting you, too'

jerry.off('greeting', say1)
jerry.emit('greeting', 'Hi')
// => 只输出:'Hi, nice meeting you, too'

链接

支持一下
扫一扫,支持 Alin
  • 微信扫一扫
  • 支付宝扫一扫