避免重复 javascript 原型定义 - 上下文问题

Avoiding repetition on javascript prototype definitions - context issue

我有一些 javascript 代码,看起来像这样 - 它非常重复,正如您所看到的,遵循一个非常明确的模式:

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;
}

我想像这样重构它:

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;
 }

但是 this 的上下文不正确,它的行为不像普通版本。

下面是一个演示工作和不工作版本的工作示例。

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);

如果有更类似 ES6 的方法来解决同样的重复问题,我也很感兴趣。

你的高阶函数看起来不错。可能是将 return 语句放在错误位置的简单错误。

function passThrough(obj, apply, name){
    obj[name] = function(param){
        this[apply][name] = param;
        return this;
    } //^^^^^^^^^^^^
}

如果您进行此修改,您的解决方案应该有效。

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;//<---move return this here
        }
        //return this;
     }