【发布时间】:2021-02-04 04:06:06
【问题描述】:
考虑到我有以下模块:
class Rectangle {
private width: number;
private height: number;
constructor(w: number, h: number) {
this.width = w;
this.height = h;
}
private area(): number {
return w * h;
}
public show(): void {
console.log(`${w} X ${h} = ${this.area()}`);
}
}
export default Rectangle;
如您所见,area 方法设置为private,因此我可以将其移出类并将其转换为普通函数。因为我不导出它,它不能从外部代码访问。
const area = (w: number, h: number): number => w * h;
class Rectangle {
private width: number;
private height: number;
constructor(w: number, h: number) {
this.width = w;
this.height = h;
}
public show(): void {
console.log(`${w} X ${h} = ${area(this.width, this.height)}`);
}
}
export default Rectangle;
如果我这样做,每次我 new Rectangle 类时,area 将不会再次创建,因此我的 Rectangle 对象将比具有 private 的对象更轻量级方法。我对么?我应该这样做还是坚持原来的 OOP 方式?
【问题讨论】:
-
该函数存在于对象原型中,因此我认为不会对性能产生太大影响,但这不是我的专业领域。至于将函数移到外面,将矩形作为参数而不是单独的宽度和高度参数更有意义。如果你走那条路,你可能根本就没有课。只需将 Rectangle 设置为具有高度和宽度的接口,并定义作用于 Rectangle 对象的函数即可。
-
接受两个数字的
area函数不是很有用。你只是在做乘法,所以你也可以抽象为multiply = (a, b) => a * b- 它可以比area更有效地重用。但是,如果area采用Rectangle,那就更好了,因为它可以与您的具体类型一起使用。必须调用area(rectangle.height, rectangle.width)并不是一个好的抽象,您仍然必须知道如何计算面积才能调用计算面积的函数。
标签: javascript typescript performance oop methods