在本机 Javascript(或 NodeJS)中,是否可以为函数调用链接对象或函数属性?

In native Javascript (or NodeJS) is it possible to chain object or function properties for a function call?

'what-if' 中的更多练习,我想知道以下是否可行:

output = convert(1200).from('mm').to('inches')

其中 'from' 和 'to' 是 'convert' 的函数(或属性),而不是更标准的:

    output = convert(1200, 'mm', 'inches')

or:

    output = convert(value = 1200, from = 'mm', to = 'inches')

附录:我猜最接近的是:

output = convert({ value: 1200, from: 'mm', to: 'inches' });
 
function convert({ value, from, to } = {}){
  // ...do stuff here...
}

使用 convert、from 和 to 函数以及属性创建一个对象构造函数,以存储调用时传递给每个相应函数的值。在 convertfrom 函数中,return 通过 'return this' 的实例和 return to 函数中的答案。

https://www.w3schools.com/JS/js_object_constructors.asp

function Converter() {
  this.value = 0;
  this.fromUnit = '';
  this.toUnit = '';
  this.convert = function(value) {
   ... 
   return this
  } 
 this.from = function(unit) {... return this} 
 this.to = function(unit) {... return answer} 
}

const converter = new Converter()
converter.convert(...).from(...).to(...)

您还可以遵循 ES6 JavaScript 上的 Class 语法。 https://www.w3schools.com/Js/js_classes.asp

是的,这是可能的。示例:

function convert(val) {
  const units = {
    mm: 1,
    cm: 10,
    dm: 100,
    m: 1000,
    in: 25.4,
    inches: 25.4,
    inch: 25.4,
    ft: 304.8,
    feet: 304.8,
    foot: 304.8,
    yd: 914.4,
    yard: 914.4,
    yards: 914.4
  }
  return {
    from(unit1) {
      return {
        to(unit2) {
          return val * units[unit1] / units[unit2];
        }
      };
    }
  };
}

const output = convert(1200).from('mm').to('inches');

console.log(output);

console.log(convert(47.24409448818898).from('inches').to('mm'));
console.log(convert(123).from('m').to('yards'));

convert returns 具有 from 方法的对象。 from returns 具有 to 方法的对象。 to returns 一个数字。临时值存储在闭包中。

将此视为语法问题而不是设计问题,这是一个丑陋但有效的解决方案。

但是,我想鼓励您重构它或重新考虑此功能 API 是否有必要。

const convert = (num) => ({
  from: (inputUnit) => {
    switch (inputUnit) {
      case "mm":
        return {
          to: (outputUnit) => {
            switch (outputUnit) {
              case "inches":
                return num / 25.4;
            }
          },
        };
    }
  },
});

console.log(
  convert(1200).from("mm").to("inches")
)