I have some javascript code which looks like this - it's very repetitive, and as you can see follows a very defined pattern:
var AttachmentBuilder = function(){
this.attachment = {};
}
AttachmentBuilder.prototype.text = function(value){
this.attachment.text = value;
return this;
}
AttachmentBuilder.prototype.fallback = function(value){
this.attachment.fallback = value;
return this;
}
AttachmentBuilder.prototype.color = function(value){
this.attachment.color = value;
return this;
}
I had the idea to refactor this like:
var AttachmentBuilder = function(){
this.attachment = {};
}
passThrough(AttachmentBuilder.prototype,"attachment","text");
passThrough(AttachmentBuilder.prototype,"attachment","fallback");
passThrough(AttachmentBuilder.prototype,"attachment","color");
function passThrough(obj, apply, name){
obj[name] = function(param){
this[apply][name] = param;
}
return this;
}
But the context of this is not correct, and it does not behave like the long-hand version.
Below is a working example demoing the working and not working versions.
var AttachmentBuilder_Original = function(){
this.attachment = {};
}
AttachmentBuilder_Original.prototype.text = function(value){
this.attachment.text = value;
return this;
}
AttachmentBuilder_Original.prototype.fallback = function(value){
this.attachment.fallback = value;
return this;
}
AttachmentBuilder_Original.prototype.color = function(value){
this.attachment.color = value;
return this;
}
var original = new AttachmentBuilder_Original();
original.text("Text").color("Red").fallback("Fallback");
console.log("original",original.attachment);
/* ------------------------------------- */
var AttachmentBuilder_New = function(){
this.attachment = {};
}
passThrough(AttachmentBuilder_New.prototype,"attachment","text");
passThrough(AttachmentBuilder_New.prototype,"attachment","fallback");
passThrough(AttachmentBuilder_New.prototype,"attachment","color");
function passThrough(obj, apply, name){
obj[name] = function(param){
this[apply][name] = param;
}
return this;
}
var adjusted = new AttachmentBuilder_New();
adjusted.text("Text").color("Red").fallback("Fallback");
console.log("adjusted",adjusted.attachment);
I'm also interested if there is a more ES6-like way of solving this same issue of repetition.
return thisinside function?