gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:21:24 25 4
gpt4 key购买 nike

我有一些 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;
} //^^^^^^^^^^^^
}

关于javascript - 避免重复 javascript 原型(prototype)定义 - 上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43677639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com