假设一个简单的类:
class Simple {
private _transactions: [];
makeTransaction() { ... }
revertTransaction() { ... }
// some other methods as well...
}
let obj = new Simple();
obj.makeTransaction(...);
obj.makeTransaction(...);
obj.revertTransaction(...);
现在,我想公开一些与报告相关的方法,我想将它们分组:
obj.reports.allTransactions();
obj.reports.reveretedTransactions();
obj.reports.clearedTransactions();
这些方法将使用Simple
类本身中的私有变量来返回一些报告。
我已经使用以下方法来实现这一目标:
class Simple {
private _test = () => { return this._transaction }
reports = {
getAll: this._test
}
}
这有效,但它有一些缺点:
reports
对象中引用它们。obj.reports.getAll
是一个属性,虽然我也可以将它作为函数调用。即便如此,我也没有得到正确的功能签名提示。有更好的方法吗?
答案 0 :(得分:2)
您可以为reports
对象创建一个类:
class Reports {
private _transactions: any[];
constructor(transactions: any[]) {
this._transactions = transactions;
}
getAll() {
return this._transactions;
}
}
class Simple {
private _transactions: any[];
public reports: Reports;
constructor() {
this._transactions = [];
this.reports = new Reports(this._transactions);
}
makeTransaction() {}
revertTransaction() { }
}
您还可以将reports
公开为类型:
interface Reports {
getAll(): any[];
}
class Simple {
private _transactions: any[];
public reports: Reports;
constructor() {
this._transactions = [];
this.reports = {
getAll: () => {
return this._transactions;
}
}
}
makeTransaction() {}
revertTransaction() { }
}
另一种选择是将报告分成不同的类,但要将Simple
实例作为其成员,并将实例的所有成员都公开。
如果您然后将Simple
转换为界面,则可以隐藏这些公共成员:
class Reports {
private _simple: SimpleImpl;
constructor(simple: SimpleImpl) {
this._simple = simple;
}
getAll() {
return this._simple.transactions;
}
}
interface Simple {
makeTransaction();
revertTransaction();
}
class SimpleImpl implements Simple {
public transactions: any[];
public reports: Reports;
constructor() {
this.transactions = [];
this.reports = new Reports(this);
}
makeTransaction() {}
revertTransaction() {}
}
如果仅显示Reports
类和Simple
界面,则公开成员仅对Reports
的实例可见。