Is it possible to write continuous nested function

2019-07-19 01:12发布

问题:

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