Javascript add to string with each function call

后端 未结 5 2395
执念已碎
执念已碎 2020-12-21 05:32

I have the following situation where I have a function f which takes an argument input.

I want to be able to have f such that

5条回答
  •  情话喂你
    2020-12-21 05:58

    In JS you can even achieve this dualitiy of a function also "being" a String. Yet this is nothing you should ever use in production code.

    const f = function _f(prefix){
      const toString = () => prefix;
      return Object.assign(function(suffix="o"){ 
        return _f(prefix + suffix);
      }, {
        valueOf: toString,
        toString
      });
    }("f");
    
    console.log(""+f('l'))
    console.log(""+f())
    console.log(""+f()('l'))
    console.log(""+f()()('l'))
    console.log(""+f()()()('l'))
    
    let foo = f()();
    let fool = foo("l");
    console.log(""+foo("l"));
    console.log(""+fool);
    console.log(""+foo("bar"));
    console.log(""+fool("bar"));

提交回复
热议问题