实现new Person('xiaoming').say('hello').sleep(2).play('js').sleep(1).say('hhh')
链式调用没什么可说的 return this 就好了,此处的 sleep 乍一看确实会引发一些思考,关键是异步之后 this 在哪里,那这个时候可以创建一个异步队列。(js event loop)
整个实现可以分为三个核心部分:
- 串接所有this (通过return this的方式)
- 把所有任务放到任务队列里面
- 通过一个next方法有序执行队列里面的任务
具体实现如下:
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
| function Person(name) { this.tasks = [] console.log(name + ': ') setTimeout(() => { this.next() }) return this }
Person.prototype = { next() { const fn = this.tasks.pop() fn && fn() }, play(thing) { const fn = () => { console.log(`Playing ${thing}`) this.next() } this.tasks.unshift(fn) return this }, say(thing) { const fn = () => { console.log(`Saying ${thing}`) this.next() } this.tasks.unshift(fn) return this }, sleep(seconds) { const fn = () => { setTimeout(() => { this.next() }, seconds * 1000) } this.tasks.unshift(fn) return this } }
new Person('xiaoming').say('hello').sleep(2).play('js').sleep(1).say('hhh')
|