如何添加像num.tf(n)这样的方法作为num.toFixed(n)的别名

我想为Number类型的toFixed()之类的方法添加一个别名tf()。示例:

let num = 1.234;
console.log(num.toFixed(1));  // prints 1.2
console.log(num.tf(2));       // should print 1.23

通过一些研究,这是可能的,但不是常规的。我只是想在私有工具中试用它,并了解有关Prototype等的更多信息,如果您不通过布道:=)

非常感谢。 通用电气。

afeijian 回答:如何添加像num.tf(n)这样的方法作为num.toFixed(n)的别名

您需要分配给Number原型

Number.prototype.tf = Number.prototype.toFixed;
let num = 1.234;
console.log(num.toFixed(1));  // prints 1.2
console.log(num.tf(2));       // should print 1.23

,

您需要在Number中创建一个名为tf的新原型。

Number.prototype.tf =Number.prototype.toFixed

Barmar应该在上面的答案中发布。

尽管您喜欢冒险,也可以创建一个新功能来查看其功能。

Number.prototype.tf=function(num){
    return parseFloat(this.valueOf().toFixed(num))
}

他们两个基本上都做同样的事情,但是第一个答案更易读。

,

我正在尝试正确关闭此功能并将其标记为已回答。感谢您提供的出色答案。我在这里不再赘述,上面的内容都很清楚。 Ciao,Greg E。

本文链接:https://www.f2er.com/3148825.html

大家都在问