gpt4 book ai didi

javascript - 如何将常用方法提取到函数中

转载 作者:行者123 更新时间:2023-12-03 12:02:18 26 4
gpt4 key购买 nike

我想提取公共(public)方法链以防止复制粘贴相同的代码。

如何以 JavaScript 方式实现?

原版

if(this.get('with_coverage')){
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("With Coverage");
}
else{
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("Without Coverage");
}

预期

var apply_style = attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline");

if(this.get('with_coverage')){
svg.append("text")
.apply_style()
.text("With Coverage");
}
else{
svg.append("text")
.apply_style()
.text("Without Coverage");
}

最佳答案

svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("With"+(this.get('with_coverage')?"":"out")+" Coverage");

Magic.

<小时/>

有些人不喜欢代码中混合那些三元运算符。在这种情况下,您可以这样做:

function applyStyleBasedOnCondition(selection, actions, condition, t, f){
actions.call(selection);
(condition ? t : f).call(selection);
}

applyStyleBasedOnCondition(svg.append("text"), function(){
this
.attr({
x: width / 2,
y: 0 - (margin.top / 2),
"text-anchor": "middle"
})
.style({
"font-size": "16px",
"text-decoration": "underline"
});
}, this.get('with_coverage'), function(){
this.text("With Coverage");
}, function(){
this.text("Without Coverage");
});

关于javascript - 如何将常用方法提取到函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25356824/

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