簡體   English   中英

如何在javascript中創建看起來像點符號的自定義函數? 例如,str.getFirstIndex();

[英]How to create custom function in javascript that looks like a dot notation? e.g., str.getFirstIndex();

我正在查看我們團隊項目的代碼,並想知道我是否可以做得更好, “干凈且易於理解”

我做了一項研究,但我找不到任何,也許是因為我不知道術語的使用?

無論如何這里是代碼:

var num = 10000;

function toShortMoney(num) {
    var thousand = Math.pow(10, 3),
        million = Math.pow(10, 6),
        billion = Math.pow(10, 9),
        negative = false,
        money = '0',
        str = '';

    str = num.toString();
    if(str.indexOf('-') > -1) {
        negative = true;
        str = str.slice(1);
        num = str.valueOf(str);
    }

    if(num < million && num >= thousand) { //thousand
        num = (Math.floor(num / thousand)).toFixed(0);
        money = num + 'K';
    }
    else if(num < billion && num >= million) { //million
        num = (num / million).toFixed(2).replace(/(\.?0+$)/,'');
        money = num + 'M';
    }
    else {
        money = Math.floor(num).toFixed(0);
    }

    if(negative)
        return '($' + money + ')';

    return '$' + money;
}

最初我可以通過將變量num作為參數來訪問ThortMoney,但是如何通過執行像函數這樣的點符號來訪問ThortMoney?

例如,num.toShortMoney(); //返回$ 10k

如果您希望此方法可用於任何數字對象,則必須將該方法添加到Number的原型中。

Number.prototype.toShortMoney = function() {
  // in the context of being called on a number, the number will
  // not be an argument, but you access it via this eg.:
  return '$' + this;
};

但是,有些人覺得在原生類的原型中添加方法是不好的做法(除了polyfilling)。但我會說大多數情況下對於圖書館項目都是如此。

祝好運

您可以在toShortMoney調整numthis ,也可以擴展String.prototype以接受toShortMoney NumberString

function toShortMoney() {
    var thousand = Math.pow(10, 3),
        million = Math.pow(10, 6),
        billion = Math.pow(10, 9),
        negative = false,
        money = '0',
        str = '';

    num = this;
    str = num.toString();
    if(str.indexOf('-') > -1) {
        negative = true;
        str = str.slice(1);
        num = str.valueOf(str);
    }

    if(num < million && num >= thousand) { //thousand
        num = (Math.floor(num / thousand)).toFixed(0);
        money = num + 'K';
    }
    else if(num < billion && num >= million) { //million
        num = (num / million).toFixed(2).replace(/(\.?0+$)/,'');
        money = num + 'M';
    }
    else {
        money = Math.floor(num).toFixed(0);
    }

    if(negative)
        return '($' + money + ')';

    return '$' + money;
}

String.prototype.toShortMoney = Number.prototype.toShortMoney = toShortMoney

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM