You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将toUSD函数改造为Number原型方法,实现(数字).toUSD()调用?

实现Number实例的toUSD格式化方法

问题描述

我有一个运行正常的全局格式化函数:

function toUSD(amount): string {
  // RETURN number in $0.00 format
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(amount);
};

当前调用方式为:

console.log(toUSD(123)); // 输出: $123.00

想要修改为通过Number实例直接调用的方式,即:

console.log((123).toUSD()); // 输出: $123.00

解决方案

要实现这种调用方式,需要将toUSD方法添加到Number的原型对象上,让所有Number实例都能继承并使用该方法。修改后的代码如下:

Number.prototype.toUSD = function(): string {
  // 方法内部的this指向调用该方法的Number实例
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(this);
};

关键说明

  • 必须通过Number.prototype挂载方法,这样所有数字实例都能访问到toUSD
  • 不要用箭头函数定义原型方法:箭头函数没有独立的this,会绑定外层作用域的上下文,无法获取当前调用的数字实例
  • 调用时注意语法:数字字面量直接跟.会被解析为小数点,所以需要用括号包裹(如(123).toUSD()),或者写成123..toUSD()、123 .toUSD()(空格分隔)

内容的提问来源于stack exchange,提问作者suchislife801

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:10:31