[英]Javascript returning value if no method chaining is available
我剛剛開始使用javascript中的方法鏈接概念。 我知道回國的this
對鏈的方法,但我在這里使用透出模塊模式。
代碼 :
var currency = (function(){
var rates = {
INR: 64.10
};
function convert(value){
return value * rates["INR"];
//"return this"? and also get the return value (if no chained mathods) ?
}
function format(){
return this.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
return {
convert: convert,
format: format
}
})();
我將以兩種不同的方式調用該函數。
但是問題是我是否return this;
從convert
函數如何#1是可能的? 如果我不從convert
函數方法返回this
鏈接,將無法進行。
問 :如果不請求鏈接,此模式中的convert()
函數應該能夠執行轉換並返回值,並且應該能夠執行鏈接?
如果格式功能錯誤,請忽略。
如評論中所述,您在OP中顯示的模式不適合鏈接。 但是您要達到的目標絕對是可以的。 瀏覽嵌入式腳本以了解如何完成此操作
let CurrencyConverter = (function() { const rates = { INR: 64.10 } // CurrencyConverter class function CurrencyConverter() { // instantiate with new // 'this' inside this function is the new instance // of CurrencyConverter this.value = 0; } // Add convert method // this method just convert the value and store it CurrencyConverter.prototype.convert = function convert(value) { this.value = value * rates["INR"]; return this; } // Add format method // this method formats the rate and // return the formatted output CurrencyConverter.prototype.format = function format() { return (this.value + "").replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, "$1,"); } // add as many more methods as you want // ... // finally return the 'class' return CurrencyConverter; })() // instantiate new converter let converter = new CurrencyConverter(); // convert console.log(converter.convert(75).format())
注意:上面的代碼段並不是100%完美的,但它只是為了說明如何在javascript中實現。
更新-1
根據評論,這是另一種方法:
let converter = (function() { // constant rates const rates = { INR: 64.10, GBP: 1.29 } // converter function return function convert(value, currency) { let _val = (value * rates[currency || "INR"]).toFixed(2) let ret = {} // value getter Object.defineProperty(ret, 'value', { get: () => _val }); // value formatter Object.defineProperty(ret, 'formatted', { get: () => (_val + "").replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, "$1,") }); return ret; } })(); // use it like console.log(converter(125).value) console.log(converter(120, "GBP").formatted)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.