我创建了一个用打字稿编写的nodejs模块,它工作正常,但我对用于将类声明的参数传递给外部函数(在类范围之外声明的函数(的方法并不是特别满意。有没有更好的方法可以在不将变量一个接一个地传递给"外部"函数的情况下做到这一点?
我知道我可以将 fooFunc 函数移动到类中,但我避免这样做,因为我不希望这个函数可用于使用结果模块的代码(我只希望 check(( 可用(,因为类被导出。
export class Foo {
private readonly a: number;
constructor(a: number) {
this.a = a;
}
async check() {
fooFunc(this.a);
}
}
async function fooFunc(a: number) {
console.log(a);
}
您可以.call
fooFunc
,以便fooFunc
内部的this
引用foo
实例,因此无需将实例变量传递给fooFunc
:
export class Foo {
readonly a: number;
constructor(a: number) {
this.a = a;
}
async check() {
fooFunc.call(this);
}
}
async function fooFunc(this: Foo) {
console.log(this.a);
}
(当然,这要求a
不private
(
您可以创建一个处理此行为的超类。这是我的解决方案
abstract class ParamCheck {
private readonly args: any[];
constructor(...args) {
this.args = args;
}
async check() {
fooFunc(this.args);
}
}
class Foo extends ParamCheck {
constructor(private a: number, private b: number) {
super(a, b);
}
}
async function fooFunc(...args) {
console.log(args);
}
new Foo(1, 2).check();
作为替代方法,您可以考虑通过将 fooFunc
的实现传递到构造函数中来组合 foo 对象。像这样:
type CheckFunc = (n: number) => any;
export class Foo {
private readonly a: number;
private readonly checkFunc: CheckFunc;
constructor(a: number, checkFunc: CheckFunc) {
this.a = a;
this.checkFunc = checkFunc;
}
async check() {
this.checkFunc(this.a);
}
}
///////
async function fooFunc(a: number) {
console.log(a);
}
const foo = new Foo(1, fooFunc);
您可能需要考虑此更改的原因是,现在可以安全地对此函数进行单元测试。依赖于对外部类的硬编码引用会违反依赖关系反转主体