这道题是一位群友发出来的,就动手实现了一下。
思路:
- machine(‘ygy’),可知 machine 函数需要传递一个参数,而后面的 execute() ,则执行打印,同时可知在执行 machine(‘ygy’) 函数之后会返回原型(machine.prototype);
- 而第二个执行中添加了 do 函数,且在执行 do 函数之后可以继续执行 exxcute 函数,可知 do 函数会 return machine.prototype,同理,wait 和 waitFirst 函数也一样;
- 一般这些链式调用,且会出现延迟时间调用的基本可以确认需要使用 Promise 来实现,而且显然有且只有一个 Promise 来进行实现,为了能实现给多个原型对象属性函数进行调用,因此会放在 machine 构造函数中进行存放;
- 又因为 Promise.resolve().then(res => ‘…’).then()…. 这个特点,在结合需要实现的链式调用,此时基本思路已经形成。
代码:
function machine(name) {
this.name = name;
this.myPromise = Promise.resolve(this.name);
this.consoleName = () => {
this.myPromise = this.myPromise.then((res) => {
return `start ${res}`;
});
};
this.consoleName();
return arguments.callee.prototype;
}
// 动作
machine.prototype.do = function (action) {
myPromise = myPromise.then((res) => {
res && console.log(res);
return `${name} ${action}`;
});
return machine.prototype;
};
// 延迟
machine.prototype.wait = function (num) {
myPromise = myPromise.then(async (res) => {
console.log(res);
console.log(`wait ${num}s`);
await new Promise((resolve) => {
setTimeout(() => {
resolve(null);
}, num * 1000);
});
});
return machine.prototype;
};
// 提前延迟
machine.prototype.waitFirst = function (num) {
myPromise = myPromise.then(async (res) => {
console.log(`waitFirst ${num}s`);
await new Promise((resolve) => {
setTimeout(() => {
resolve(null);
}, num * 1000);
});
return res;
});
return machine.prototype;
};
// 执行
machine.prototype.execute = async function () {
myPromise.then((res) => {
console.log(res);
});
};
// machine("小卡车").execute();
// machine("小卡车").do("吃东西").execute();
// machine("小卡车").wait(3).do("吃东西").execute();
machine("小卡车").waitFirst(3).do("吃东西").execute();
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END