有没有一种优雅的方式来 "simulate" 通过引用传递 getter ?
Is there a graceful way to "simulate" passing a getter by reference?
我有以下 class...
class Order {
constructor() {
// ...
}
get subtotal() { return this.items.reduce((sum, {price}) => sum+price, 0); }
}
...和一个名为 PaymentSummary
的组件,我想在其中引用 Order.subtotal
。但是,与 getters 的情况一样,我只能通过值 subtotal
.
Pseudo/simplified:
let order = new Order(); //subtotal: 15.00
let paymentSummary = new PaymentSummary(order.subtotal);
order.items.push( {price: 100.00} ); //subtotal: 115.00
console.log( paymentSummary.subtotal ); //15.00
显而易见的解决方案是使 subtotal
成为 方法 而不是 getter,就像这样:
class Order {
constructor() {
// ...
}
function subtotal() { return this.items.reduce((sum, {price}) => sum+price, 0); }
}
现在我可以将 Order.subtotal
作为函数引用传递给我们了。
但是,这是唯一的解决方案吗?
也许我过于谨慎或者只是以错误的方式处理这个问题,但订单数据现在是属性和方法的混合包,这似乎有点奇怪。
我考虑过整个 order
,但考虑到它的 size/complexity(多个嵌套 classes,以及它们自己的嵌套 classes 等),即似乎是个坏主意。
鉴于 SO 需要具体问题,我想我的问题可以归结为:是否有一种方法可以传递对计算值的引用,以便检索它不需要 执行吗?
Is there a way to pass a reference to a calculated value such that retrieving it doesn't require executing it?
没有。传递函数或传递带有 getter 属性 的对象是您唯一的选择。两者都是完全合理的,尽管该函数明显表明结果可能会发生变化 - 对象发生变化 "on its own" 可能会造成混淆。
我有以下 class...
class Order {
constructor() {
// ...
}
get subtotal() { return this.items.reduce((sum, {price}) => sum+price, 0); }
}
...和一个名为 PaymentSummary
的组件,我想在其中引用 Order.subtotal
。但是,与 getters 的情况一样,我只能通过值 subtotal
.
Pseudo/simplified:
let order = new Order(); //subtotal: 15.00
let paymentSummary = new PaymentSummary(order.subtotal);
order.items.push( {price: 100.00} ); //subtotal: 115.00
console.log( paymentSummary.subtotal ); //15.00
显而易见的解决方案是使 subtotal
成为 方法 而不是 getter,就像这样:
class Order {
constructor() {
// ...
}
function subtotal() { return this.items.reduce((sum, {price}) => sum+price, 0); }
}
现在我可以将 Order.subtotal
作为函数引用传递给我们了。
但是,这是唯一的解决方案吗?
也许我过于谨慎或者只是以错误的方式处理这个问题,但订单数据现在是属性和方法的混合包,这似乎有点奇怪。
我考虑过整个 order
,但考虑到它的 size/complexity(多个嵌套 classes,以及它们自己的嵌套 classes 等),即似乎是个坏主意。
鉴于 SO 需要具体问题,我想我的问题可以归结为:是否有一种方法可以传递对计算值的引用,以便检索它不需要 执行吗?
Is there a way to pass a reference to a calculated value such that retrieving it doesn't require executing it?
没有。传递函数或传递带有 getter 属性 的对象是您唯一的选择。两者都是完全合理的,尽管该函数明显表明结果可能会发生变化 - 对象发生变化 "on its own" 可能会造成混淆。