37宣讲前端的一道题目

用JS实现一个英雄类HEro ,可以接受以下方式调用
hero("aaa")
输出 hi this is aaa
hero("aaa").kill(1).recover(30)
输出 hi this is aaa
kill 1 bug(1s所以不是bugs)
recover30 bloods
hero("aaa").sleep(10).kill(2)
输出 hi this is aaa
暂停10秒
kill 2 bugs

一开始我用的构造函数+原型写了一个类貌似不对
有没有其他的解决方案?
还有sleep10如何实现?用一个空的while循环?
求会的dalao~dalao~指导
全部评论
类似JQ的链式调用 ;(function(){ window.Hero = function(name, num, bloods){ console.log(this.name); return new _Hero(name, num, bloods); }; function _Hero(name, num, bloods) { this.name = name; this.num = num; this.bloods = bloods; return this; }; _Hero.prototype = { constructor : _Hero, kill: function () { if (this.num === 1) { console.log("kill " + this.num + " bug"); } else { console.log("kill " + this.num + " bugs"); } return this; }, recover: function () { if (this.bloods === 1) { console.log("recover " + this.bloods + " blood"); } else { console.log("recover " + this.bloods + " bloods"); } return this; }, sleep: function () { setTimeout((function () { // 等待 console.log(' '); })(), 10000); return this; } }; })(); Hero("aaa").sleep(10).kill(2);
点赞 回复 分享
发布于 2017-09-18 17:59
class Hero { constructor (name) { this.name = name console.log(`hi this is ${this.name}`) } kill (num) { let complex = (num === 1) ? 'bug' : 'bugs' console.log(`kill ${num} ${complex}`) return this } recover (num) { let complex = (num === 1) ? 'blood' : 'bloods' console.log(`recover ${num} ${complex}`) return this } sleep (time) { let now = +new Date() while (+new Date() - now < time * 1000) {} return this } } new Hero('aaa').sleep(10).kill(2).recover(1) 不想写原型啊什么的,用的ES6 不知道是不是这么个意思, JS单线程还想玩sleep,那我只能循环了。。 希望有大佬能给出好答案吧
点赞 回复 分享
发布于 2017-09-18 18:46

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务