如何在TS中使用对象文字来替换复杂的切换情况



我有以下场景:在交换机中,我根据情况调用两个不同的函数。第一个函数具有args"0";A";以及";B";它们是数字并且第二函数具有arg"0";C";它是一个字符串。

现在我想知道是否可以将这个switch语句转换为对象文字。

我的TS代码:

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
result: string = null;
v: number = 1;
firstFn(a: number, b: number) {
console.log(1);
if (a == undefined && b == undefined) return 'missingParam';
return a == b ? 'Equal' : 'Not';
}
secondFn(c: string) {
console.log(2);
return c ? c : 'noParam';
}
doStuff() {
const opt = {
0: this.firstFn.apply(this, [1, 1]),
1: this.secondFn.apply(this, ['k']),
};
this.result = opt[this.v];
//Toggle between the two functions
this.v == 1 ? this.v-- : this.v++;
}
}

我的HTML代码:

<button (click)="doStuff()">Do stuff</button>
{{ result }}

以下是我在stackblitz中的尝试:https://stackblitz.com/edit/angular-9-starter-kq1nrx

我现在面临的问题是;doStuff(("函数附加到对象属性的两个函数都是计算的,而不仅仅是选择的函数。(您可以通过检查stackblitz中的控制台来检查(

有没有办法避免这种双重函数调用?如果是,如何?

答案是用.bind()替换.apply()。Bind不会调用函数,因此不会触发这两个日志。

此外,请注意,现在您应该在获得引用时调用函数:

this.result = opt[this.v]();

更新代码:

doStuff() {
const opt = {
0: this.firstFn.bind(this, [1, 1]),
1: this.secondFn.bind(this, ['k']),
};
this.result = opt[this.v]();
//Toggle between the two functions
this.v == 1 ? this.v-- : this.v++;
}

最新更新