我刚刚开始了解 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
}
})();
我将以两种不同的方式调用该函数。
- 货币.convert(100);//6410;现在它返回率,这是 预计
- currency.convert(1000).format();//64,100;这是预期的
但问题是,如果我从 convert
函数中 return this;
,#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)
关于如果没有可用的方法链接,Javascript 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45891668/