2017-08-26 95 views
0

我刚刚开始使用javascript中的方法链接概念。我知道链接方法返回this,但我在这里使用揭示模块模式。如果没有方法链接,则Javascript返回值

代码

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 
    } 
})(); 

,我会打电话的功能,在两种不同的方式。

  1. currency.convert(100); // 6410;现在它返回率,这是 预计
  2. currency.convert(1000).format(); // 64100;这是预期

但问题是,如果我return this;convert功能如何将#1是可能的吗?如果我不从convert返回this函数方法链接将不可能。

Qconvert()在这种模式下的函数应该能够执行转换并返回值,如果没有请求链接并且应该能够执行链接?

如果格式函数错误,请忽略。

+0

这种模式不适合链接 –

+0

,我曾经听到的唯一一个做这样的事情是'lodash'链,它使用包装来链接一些方法。 – MinusFour

+0

你不需要“揭示模块模式”。 ES6有实际的模块。使用它们。关于链接,链式时尚已经结束。没有人这样做。它基本上与jQuery一起消亡。 – 2017-08-26 05:05:42

回答

1

如评论中所述,您在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)

+0

+1感谢您的片段。看起来不错但对原型方法不感兴趣。如果我没有得到任何其他答案,我会标记答案 –

+0

结帐替代方法的更新答案 –