1 回答

TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
發(fā)生這種情況是因為您從鏈中的最后一個調(diào)用 next (checkEqualThirty()) - 但沒有下一個,因此默認(rèn)答案分配為nextHandler-null因此null返回并 console.logged。
你已經(jīng)沒有給自己留下退路了。我修改了代碼,以便您在 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));
添加回答
舉報