方法連結

方法鏈是一種程式設計策略,可以簡化程式碼並對其進行美化。通過確保物件上的每個方法返回整個物件而不是返回該物件的單個元素來完成方法連結。例如:

function Door() {
    this.height = '';
    this.width = '';
    this.status = 'closed';
}

Door.prototype.open = function() {
    this.status = 'opened';
    return this;
}

Door.prototype.close = function() {
    this.status = 'closed';
    return this;
}
Door.prototype.setParams = function(width,height) {
    this.width = width;
    this.height = height;
    return this;
}

Door.prototype.doorStatus = function() {
    console.log('The',this.width,'x',this.height,'Door is',this.status);
    return this;
}

var smallDoor = new Door();
smallDoor.setParams(20,100).open().doorStatus().close().doorStatus();

請注意,Door.prototype 中的每個方法都返回 this,它指的是該 Door 物件的整個例項。