如何在javascript中进行链接并在两者之间获得价值

如何在javascript中进行链接并在两者之间获得价值,javascript,chaining,Javascript,Chaining,好吧,奇怪的标题,我知道。然而,问题很简单。在课堂上,我希望能够做到以下两件事: invoice.getAmount();//返回1000 及 invoice.getAmount().asCurrency();//返回$1000.00 我也可以,只是不知道如何让两者都发挥作用 关于第二个想法,我现在的想法是: getAmount() { this._temp = this.amount; return this; } asCurrency(){ if(this._temp){

好吧,奇怪的标题,我知道。然而,问题很简单。在课堂上,我希望能够做到以下两件事:

invoice.getAmount();//返回1000

invoice.getAmount().asCurrency();//返回$1000.00

我也可以,只是不知道如何让两者都发挥作用

关于第二个想法,我现在的想法是:

getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}
这是一个丑陋的副本,我真的有,但概念是代表

有什么想法吗


谢谢

记住
getAmount
返回的是一个数字

因此,除非
Number
原型上存在
asCurrency
,否则无法在
getAmount
的返回值上链接
asCurrency
(不使用)


如果您想在不修改
Number
原型的情况下在类中保持所有这些内容的组合,您需要使用
valueOf
(最佳解决方案),或者将
getAmount
的返回值设置为类实例,以便可以将其与
asCurrency

链接,您可以覆盖一些内置项(和)诸如此类:

功能发票(金额){
这个。金额=金额;
}
Invoice.prototype.toString=
Invoice.prototype.valueOf=函数valueOf(){
返回此.value;
};
Invoice.prototype.getAmount=函数getAmount(){
this.value=this.amount;
归还这个;
};
Invoice.prototype.asCurrency=函数asCurrency(){
this.value='$'+this.value.toFixed(2);
归还这个;
};
var发票=新发票(1000);
console.log(编号(invoice.getAmount());
log(字符串(invoice.getAmount().asCurrency());
//或者更微妙地
console.log(invoice.getAmount()+0);

console.log(invoice.getAmount().asCurrency()+“”)
技巧是使用
valueOf()
方法

class Invoice {

  constructor(value) {
    this.value = value;
  }

  getAmount() {
    return {
      valueOf: _ => this.value,
      asCurrency: _ => '$' + this.value
    }
  }
}

const i = new Invoice(150);

console.log(i.getAmount() + 10); // 160
console.log(i.getAmount().asCurrency()); // '$150'
您可以使用:

函数getAmount(){ 返回1000; } var result=getAmount().ToLocalString('en-en',{style:'currency',currency:'USD'});
控制台日志(结果)您应该在Javascript类型的数字中添加一个原型函数asCurrency()。。。或者,如果您不想修饰内置原型对象,可以使用返回普通数值的
.valueOf()
方法和返回格式化字符串的
.asCurrency()
方法返回对象。这是一个好主意。“我如何链接?”——“不”???这基本上就是你说的吗?因为我看不出这是如何解决这个问题的。@PatrickRoberts试试这个:
Number(1000)。toLocaleString('en-en',{style:'currency',currency:'USD'})
我只是指出,没有必要实现新的东西来获取
asCurrency()
,因为
Number.prototype.toLocaleString()
谢谢,我们以前试过,不幸的是,我们有自定义货币显示。。。不要问看起来很简单,很优雅。让我试试看,如果它符合我的要求,我会把你作为答案。谢谢,但我最终还是使用了@ankr解决方案。你的要求我在返回值上使用Number/String。@RomainGonçalvès我可能应该指出,他的解决方案也要求这样,他只是用
+10
隐式调用
valueOf()
,我喜欢这个答案。我认为它更清晰,更易于维护。