函数链式调用

编写代码,满足以下条件:
(1)Hero(“37er”);执行结果为 Hi! This is 37er
(2)Hero(“37er”).kill(1).recover(30);执行结果为 Hi! This is 37er Kill 1 bug Recover 30 bloods
(3)Hero(“37er”).sleep(10).kill(2)执行结果为 Hi! This is 37er //等待 10s 后 Kill 2 bugs
//注意为 bugs (双斜线后的为提示信息,不需要打印)

分析题目,主要考察函数的链式调用如何实现。实现代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function Hero (name) {
let o = Object.create(null);
o.name = name;
o.time = 0;
let result = `Hi! This is ${name}`;
console.log(result);
o.kill = function(num){

if (o.time) {
setTimeout(()=> {
console.log(`Kill ${num} bug${num > 1 ? 's': ''}`);
}, o.time * 1000);
} else {
if (num <= 1) {
console.log(`Kill ${num} bug`);

} else {
result = (!o.time ? result : '' )+ ` Kill ${num} bug${num > 1 ? 's': ''}`;
console.log(result);
}
}
return o;
};
o.sleep = function(timer) {
o.time = timer;
return o;
};
o.reverse = function(timer) {
console.log(`Recover ${timer} bloods`);
return o;
}
return o;
}

<!-- 测试代码 -->
// Hero("37er");
// Hero("37er").kill(1).reverse(30)
Hero("37er").sleep(2).kill(2)

总结

链式调用的核心代码就是 return o;。