Is it possible to write continuous nested functions in JavaScript?

北慕城南 提交于 2020-01-04 14:15:02

问题


I know this is the realm of closures and what not. But is it possible to continuously call nested anonymouse funtions?

Say I have this:

function testing(input) {

  var testing = 0;
  (function() {
    testing = testing + 1;
  })()

  return "testing";
}

Can we have something like this testing()()()()()()() ?


回答1:


You could use an inner function which makes the update and has a toString method to get a primitive value.

function testing() {
    function fn() {
        string += ++counter;
        return fn;
    }

    var counter = 0, 
        string = 'foo';

    fn.toString = _ => string;
    return fn();
}

console.log(testing());
console.log(testing()());
console.log(testing()()());


来源:https://stackoverflow.com/questions/48889069/is-it-possible-to-write-continuous-nested-functions-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!