1 回答
TA贡献1829条经验 获得超9个赞
发生这种情况是因为您从链中的最后一个调用 next (checkEqualThirty()) - 但没有下一个,因此默认答案分配为nextHandler-null因此null返回并 console.logged。
你已经没有给自己留下退路了。我修改了代码,以便您在 pass 方法中容纳其他可能性。
/** Chain **/
const Chain = function(handler) {
this.handler = handler;
this.nextHandler = null;
}
Chain.prototype.setNextHandler = function(nextHandler) {
this.nextHandler = nextHandler;
return nextHandler;
}
Chain.prototype.pass = function(...args) {
let result = this.handler(...args);
if (result === 'next' && this.nextHandler !== null) {
result = this.nextHandler.pass(...args);
} else if (result === 'next') {
result = "Not found";
}
return result;
}
/** Handlers **/
const equalTen = function(number) {
return (number === 10) ? 'equal-ten' : 'next';
}
const equalTwenty = function(number) {
return (number === 20) ? 'equal-twenty' : 'next';
}
const equalThirty = function(number) {
return (number === 30) ? 'equal-thirty' : 'next';
}
/** Controller **/
const chainController = function(number) {
const checkEqualTen = new Chain(equalTen);
const checkEqualTwenty = new Chain(equalTwenty);
const checkEqualThirty = new Chain(equalThirty);
checkEqualTen
.setNextHandler(checkEqualTwenty)
.setNextHandler(checkEqualThirty);
return checkEqualTen.pass(number);
};
//is problem, when external call him, always get null
console.log(chainController(5));
console.log(chainController(10));
console.log(chainController(15));
console.log(chainController(20));
console.log(chainController(25));
console.log(chainController(30));
console.log(chainController(35));
添加回答
举报