方法链接
方法链是一种编程策略,可以简化代码并对其进行美化。通过确保对象上的每个方法返回整个对象而不是返回该对象的单个元素来完成方法链接。例如:
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
对象的整个实例。