[英]Accessing/Calling a class method from another class in mediator pattern javascript
class Customer {
constructor(name) {
this.name = name;
}
send(amount, to) {
new GooglePay().send(amount, this, to);
}
receive(amount, from) {
console.log(`Payment of ${amount} from ${from} to ${this.name} is succesful`);
}
}
問題是基於調解人模式。 所以上面我已經定義了我可以發送和接收資金的客戶。 因此,我構建了一個名為 GooglePay 的類,用於調解客戶之間的交易。 客戶有發送功能,通過它可以匯款,它需要 2 個參數(金額,到)
該函數應該實際調用或被 GooglePay 實例接收,然后在檢查接收者是否注冊后將金額發送給接收者
class GooglePay {
constructor() {
this.customerBase = [];
}
register(name) {
this.customerBase.push(name);
return this;
}
send(amount, from, to) {
if (this.customerBase.filter(cust => cust === to)) {
to.receive(amount, from);
} else {
console.log('This customer does not exist');
}
}
}
請幫助我,我被卡住了,我不明白如何從一個類訪問其他類的方法。
所以我為我的問題找到了正確的解決方案,請查看:
class Customer {
constructor(name) {
this.name = name;
this.googlepay = null;
}
send_money(amount, to) {
this.googlepay.transaction(amount, this, to);
}
receive_money(amount, from) {
console.log(`payment of ${amount} from ${from} to ${this.name} is succesful`);
}
}
class GooglePay {
constructor() {
this.customer_base = [];
}
register_customer(customer_class) {
this.customer_base.push(customer_class);
customer_class.googlepay = this;
}
transaction(amount, from, to) {
this.customer_base.filter(cust => {
if (cust.name === to) {
cust.receive_money(amount, from.name);
}
});
}
}
仔細觀察,您可以在我的客戶類構造函數中看到一個名為this.googlepay = null
的屬性
這就是訣竅所在。 Cheerios mate 很好地解決了這個難題。
如果您要調用js
類(自ECMAScript 2015 (6th Edition, ECMA-262) 起),是否使用任何框架都沒有關系。 要從類調用函數或屬性,您可以像這樣:
//expecting that the class is in another file but same directory
const Gpay = require('./googlePay'); //<-- don't need the .js file extension
const googlePay = new GPay();
現在你可以像這樣使用這個類:
googlePay.register('Name');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.