减少javascript代码
在我的angular项目中有两个函数,一个是aceitaProposta,它执行以下操作:减少javascript代码,javascript,angular,oop,Javascript,Angular,Oop,在我的angular项目中有两个函数,一个是aceitaProposta,它执行以下操作: aceitaProposta() { this.aceita(); // some other code } 我有一只水龙: 现在,this.recusa和this.aceita之间的唯一区别是,第一个函数增加属性,第二个函数减少属性。我想知道是否有一种方法可以将这两个函数转换成一个函数,只需使用if之类的东西来确定它是递减还是递增。这样,我将在aceitaProposta和recusa
aceitaProposta() {
this.aceita();
// some other code
}
我有一只水龙:
现在,this.recusa和this.aceita之间的唯一区别是,第一个函数增加属性,第二个函数减少属性。我想知道是否有一种方法可以将这两个函数转换成一个函数,只需使用if之类的东西来确定它是递减还是递增。这样,我将在aceitaProposta和recusaProposta中调用相同的函数。例如:
aceitaProposta() {
this.incrementDecrement();
// some other code
}
recusaProposta() {
this.incrementDecrement();
// some other code
}
应该很容易
function incrementDecrement(inc: boolean)
{
inc ? this.prop++ : this.prop--;
}
应该很容易
function incrementDecrement(inc: boolean)
{
inc ? this.prop++ : this.prop--;
}
@金菲利克斯有。只需传递一个布尔值
incrementDecrement(shouldIncrement: boolean) {
shouldIncrement ? value++ : value--;
}
aceitaProposta() {
this.incrementDecrement(true);
}
recusaProposta() {
this.incrementDecrement(false);
}
@金菲利克斯有。只需传递一个布尔值
incrementDecrement(shouldIncrement: boolean) {
shouldIncrement ? value++ : value--;
}
aceitaProposta() {
this.incrementDecrement(true);
}
recusaProposta() {
this.incrementDecrement(false);
}
另一种方法是使用ES6和更多“功能性”代码。将参数设置为函数而不是布尔值。然后对传递的函数进行更改
update(alteration) {
x = alteration(x);
}
aceitaProposta() {
this.update((x) => x - 1);
}
recusalProposta() {
this.update((x) => x + 1);
}
没有ES6有点难看,但您只需添加匿名函数声明。另一种方法是使用ES6和更多“功能性”代码。将参数设置为函数而不是布尔值。然后对传递的函数进行更改
update(alteration) {
x = alteration(x);
}
aceitaProposta() {
this.update((x) => x - 1);
}
recusalProposta() {
this.update((x) => x + 1);
}
没有ES6有点难看,但您只需添加匿名函数声明。当然,您可以向函数传递布尔值,以指示值是递增还是递减。this.add1,this.add-1。为什么需要一个函数来完成两件不同的事情?最好将它们分开,而不是将控制流添加到本应简单的对象中。当然,可以将布尔值传递给函数,以指示值是递增还是递减。this.add1,this.add-1。为什么需要一个函数来执行两个不同的操作?最好将它们分开,而不是将控制流添加到本应简单的内容中。最好是这样。prop+=inc-!股份有限公司;为清晰起见,请使用if/else语句。他们已将问题标记为angular,因此我认为在此处也可以显示打字脚本答案。最好是this.prop+=inc-!股份有限公司;为了清楚起见,使用if/else语句。他们用angular标记了这个问题,所以我认为在这里也显示一个打字稿答案是很好的。哦,就是这样。非常感谢,就这样。非常感谢你