將執行函數放入數組隊列,使用next() 執行,將調用函數賦值給構造函數的原型,可以進行連續鏈式調用,必要:執行功能函數需要返回this
let index = 0; let stack = []; function next() { let fn = stack[index]; index++; if (typeof fn === 'function') { fn(); } } function Man(name) { stack.push(function () { console.log("Hi! This is " + name); next(); }) } var Person = function (name) { return new Man(name) } Man.prototype.sleep = function (time) { stack.push(function () { setTimeout(function () { console.log("Wake up after " + time) next() }, time * 1000) }) return this; } Man.prototype.eat = function (food) { stack.push(function () { console.log('Eat ' + food) next(); }) return this; } Man.prototype.sleepFirst = function (time) { stack.unshift(function () { setTimeout(function () { console.log('wake up after ' + time) next() }, time * 1000) }) return this; } // Person('Li') /* 輸出: Hi! This is Hank! */ // Person('Dan').sleep(3).eat('dinner') /* 輸出: Hi! This is Hank! // 等待10秒.. Wake up after 10 Eat dinner~ */ // Person('Jerry').eat('dinner~').eat('supper~') /* 輸出: Hi This is Hank! Eat dinner~ Eat supper~ */ Person('Smith').sleepFirst(2).eat('supper') /* 等待5秒,輸出 Wake up after 5 Hi This is Hank! Eat supper */ next()
備注:次代碼段摘抄網上經典面試題