地球ウォーカー2

Scala, Python の勉強日記

カスケード

Good Partsに載ってる、メソッドチェーン的なアレ。
メソッドの中でthisを返すようにするだけで実現できる。
ググってもあんまり出てこないけど、一般的な言葉じゃないんだろうか。

function Box(h, w, c) {
  this.height = h;
  this.width  = w;
  this.color  = c;
}

Box.prototype.setWidth = function(w){
                           this.width = w;
                           return this;
                         }

Box.prototype.setHeight = function(h){
                           this.height = h;
                           return this;
                         }

Box.prototype.setColor = function(c){
                           this.color = c;
                           return this;
                         }

var box = new Box(100, 100, 'Blue');
console.log(box.width);    // 100
console.log(box.height);   // 100
console.log(box.color);    // Blue

box.setWidth(50)
   .setHeight(30)
   .setColor('Red');

console.log(box.width);    // 100
console.log(box.height);   // 30
console.log(box.color);    // Red