写一个链式调用,调用方式如下:new Man('lan').sleep(3).eat('apple').sleep(3).eat('banana');输出:hello, lan -->(停顿3s) --> lan eat apple -->(停顿3s) --> lan eat banana我的代码如下:class Man { constructor(name) { this.name = name; this.sayName(); } sayName() { console.log('hi '+this.name); } sleep(time) { var self = this; new Promise((res, rej)=> { setTimeout(()=> { res(''); }, time*1000) }).then(val=> { return self; }); } eat(food) { console.log(this.name + '吃' + food); return this; }}new Man('兰兰').sleep(3).eat('饼干').sleep(3).eat('苹果');问题出在sleep这个节点上,尽管用了promise还是不能及时返回this指针,导致sleep(3).eat('...')时报错说没有eat函数。请问应该怎么解决呢?
添加回答
举报
0/150
提交
取消
