前端面试题 小明早餐午餐晚餐
如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!
前端面试题 小明早餐午餐晚餐
Human('小明').sleep(2).eat('早餐').sleep(3).eat('午餐').sleep(4).eat('晚餐').sleepFirst(1);需要让它输出如下内容 开始等待1秒 你好,小明 休息2秒 小明吃了早餐 休息3秒 小明吃了午餐 休息4秒 小明吃了晚餐 请编写Human的javascript代码 提示说明: Human('aa') 输出:你好,aa sleepFirst(n);在所有方法执行前之前等待n秒 sleep(n) 在等待n秒之后,执行后面的方法 eat('xx') 输出 aa吃了xx
function Human(name) {
if (this && this instanceof Human) {
this.name = name;
this.callStack = [function() {
console.log('你好,' + this.name);
}];
} else {
return new Human(name);
}
}
Human.prototype.sleep = function(second) {
var self = this;
setTimeout(function() {
console.log('等待' + second + '秒');
self.callStack.shift().call(self);
}, second * 1000);
return this;
}
Human.prototype.eat = function(food) {
this.callStack.push(function() {
console.log(this.name + '吃了' + food);
});
return this;
}
Human.prototype.sleepFirst = function(second) {
console.log('休息' + second + '秒');
this.callStack.shift().call(this);
return this;
}
Human('小明').sleep(2).eat('早餐').sleep(3).eat('午餐').sleep(4).eat('晚餐').sleepFirst(1);
运行上述代码得到结果如下

- 分类:
- Web前端
更新时间:
上一篇:下一篇: