Javascript 添加到每个函数调用的字符串 [英] Javascript add to string with each function call

查看:28
本文介绍了Javascript 添加到每个函数调用的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况,我有一个函数 f,它接受一个参数 input.

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

我希望能够让 f 满足以下输出:

I want to be able to have f such that it satisfies the following output:

f('l') -->fl

f() -->

f()('l') -->fo

f()()('l') -->傻瓜

f()()()('l') -->傻瓜

我认为这可以通过以下方式实现:

I thought this would be achievable with:

function f(input) {
  let str = 'f'
  if (input) {
    return `${str}${input}`
  }
  str = `${str}o`
  return f()
}

然而这最终会陷入无限循环.我也试过让 f 返回一个函数,但这也不起作用.

However this ends up in an infinite loop. I also tried having f return a function, but this too does not work.

如何编写 f 以获得所需的输出,同时保持函数无状态?

How can I write f in order to get my desired output while keeping the function stateless?

推荐答案

在 JS 中,你甚至可以实现函数的这种二元性,同时也是"一个字符串.然而,这不是您应该在生产代码中使用的东西.

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"));

这篇关于Javascript 添加到每个函数调用的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆