三七互娱秋招web前端笔试题编程题(使用原生JS实现一个英雄类Hero, 可以按照以下方式调用正确输出)

使用原生JS实现一个英雄类Hero, 可以按照以下方式调用(考察点: JavaScript流程控制)
(1) Hero("37FEer")输出:
    Hi!This is 37FEer!
(2) Hero("37FEer").kill(1).recover(30)输出:
    Hi!This is 37FEer!
    Kill 1 bug (注意:数量1个,所以bug是单数);
    Recover 30 bloods;
(3) Hero("37FEer").sleep(10).kill(2)输出:
    Hi!This is 37FEer!
    // 等待10秒..
    Kill 2 bugs (注意:数量2个,所以bugs是复数);

分析:这个感觉有点难,因为我自己只能同时实现其中某一个(第二个或者第三个),但是不能同时实现上述三种输出。

比如博主这里先提供实现第二种的代码(主要逻辑就是要明白链式调用,函数或方法每次执行后返回当前的对象):

function Hero(name){
	this.name = name;
	this.nameDesc = 'Hi! This is ' + this.name + '!';
	this.kill = function(killNum){
		this.killNum = killNum;
		this.bugDesc = 'bug;';
		if(this.killNum > 1){
			this.bugDesc = 'bugs;';
		}
		this.killNumDesc = 'Kill ' + this.killNum + ' ' + this.bugDesc;
		return this;
	};
	this.recover = function(recoverNum){
		this.recoverNum = recoverNum;
		this.recoverNumDesc = 'Recover ' + this.recoverNum + ' bloods;';
		return this.nameDesc + '\n' + this.killNumDesc + '\n' + this.recoverNumDesc;
	};
	this.sleep = function(t){
		setTimeout(function(){
			return this;
		},t*1000)
	}
	return this;
}

console.log(Hero('37FEer').kill(2).recover(30))

输出如下图:

可惜很明显的是,只有在条件为Hero('37FEer').kill(2).recover(30)才能满足,而且里面的sleep方法不能用setTimeout!理由我就不再多说了。

关键在于不知道这道题输出的形式是什么?是就在函数里console.log()打印呢?还是调用整个函数之后,return的结果。

下面是在函数里打印console.log()输出的实现,下面是改进的地方:

function Hero(name){
	this.name = name;
	console.log('Hi! This is ' + this.name + '!');
	this.kill = function(killNum){
		this.killNum = killNum;
		this.bugDesc = killNum === 1 ? 'bug' : 'bugs';
		console.log(this.killNumDesc = 'Kill ' + this.killNum + ' ' + this.bugDesc);
		return this;
	};
	this.recover = function(recoverNum){
		this.recoverNum = recoverNum;
		console.log(this.recoverNumDesc = 'Recover ' + this.recoverNum + ' bloods;');
		return this;
	};
	this.sleep = function(t){//这里千万不能用setTimeout
		var wait = t*1000;
		var start = new Date().getTime();
		var end  = start;
		while(end < start + wait){
			end = new Date().getTime();
		}
		return this;
	}
	return this;
}
console.log(Hero('37FEer'))
console.log(Hero('37FEer').kill(2).recover(30))
console.log(Hero('37FEer').sleep(1).kill(2))

如果是在函数里console.log()那么这道题就是这么实现了....

如果读者有更好更全的方法,欢迎评论交流~ 

猜你喜欢

转载自blog.csdn.net/Charles_Tian/article/details/82495351