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

时间:2017-04-28 10:09:40

标签: javascript this es6-modules

我有一些看起来像这样的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的方法来解决同样的重复问题。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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