チェイニング
重要度:2
ladder
オブジェクトがあり、上り下りできます
let ladder = {
step: 0,
up() {
this.step++;
},
down() {
this.step--;
},
showStep: function() { // shows the current step
alert( this.step );
}
};
今、シーケンスで数回呼び出す必要がある場合、次のように行います。
ladder.up();
ladder.up();
ladder.down();
ladder.showStep(); // 1
ladder.down();
ladder.showStep(); // 0
up
、down
、showStep
のコードを変更して、次のように呼び出しをチェーン可能にします。
ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0
そのようなアプローチは、JavaScriptライブラリ全体で広く使用されています。
解決策は、すべての呼び出しからオブジェクト自体を返すことです。
let ladder = {
step: 0,
up() {
this.step++;
return this;
},
down() {
this.step--;
return this;
},
showStep() {
alert( this.step );
return this;
}
};
ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0
1行あたり1つの呼び出しを書くこともできます。長いチェーンでは、より読みやすくなります。
ladder
.up()
.up()
.down()
.showStep() // 1
.down()
.showStep(); // 0