scope calling functions inside functions

2019-03-11 23:30发布

问题:

Hope somebody finds the time to explain little about functions in functions and scoping. I am trying to understand little more on functions and scope of variables and found a quite good tutorial, but this part I just do not get.

The task:

Create a function sum that will work like that: sum(a)(b) = a+b and accepts any number of brackets. Examples:

sum(1)(2) == 3
sum(5)(-1)(2) == 6

The solution:

function sum(a) {

    var sum = a;

    function f(b){
        sum += b;
        return f;
    }

    f.toString = function() { return sum };

    return f;         //line 12
}

alert( sum(1)(2) );   // 3e

The Explanation:

To make sum(1) callable as sum(1)(2), it must return a function. The function can be either called or converted to a number with valueOf. The solution is really self-explanatory:

My interpretation:

This f in function f(b) returned to the scope, which is from line 02 - 12. The f in f.toString, is the currently returned f from function(b) The next return f returns to the scope which is outside the function sum(a).

Problem:

I cannot figure out, where I need to think differently, because like I described above, the function would not be called again, so where is the part of the code, that make the 'several parentheses' possible?

Moreover, did I correctly assume where the fs are returned? Would be great if somebody would give some explanations.

回答1:

The function sum returns a function, which we refer to as f.

The function f also returns a function: in fact, the function f returns itself.

When the function f is defined inside of sum, it gets permanent access to all variables currently visible in the scope chain. Here, it includes the locally-defined variable sum (the local running sum tally) and f (the function itself). (A "closure" is what we call the functional code of f along with all its in-scope variables.)

Because f returns itself, you can chain f with repeated calls:

var this_is_f = sum(1);
var same_f_again = this_is_f(2);
var f_a_third_time = same_f_again(3);

Or simply:

sum(1)(2)(3);

It is important to note that in my first example, I don't create new functions; instead, I just refer to the exact same function object with three different identifiers.

Each call to sum creates a brand-new f with a new local sum in its scope (here, I mean the local sum defined on the first line of the function named sum). However, calling the function sum does not clobber any old f, because each call to sum instantiates a new f (and knows nothing about any other fs that have been created on prior calls to sum). That way, you can have multiple tallies running:

var first_tally = sum(1)(2);   // first: 3
var second tally = sum(4)(5);  // second: 9
first_tally(3);   // first: 6
second_tally(6);  // second: 15

The reason you're able to see a meaningful result at any time is that f stingifies to the value of sum, instead of showing you its source code.



回答2:

If you take this code and simplify it to the bare minimum I would be easier to understand. Take a function add that sums only 2 numbers:

function add(x,y) {
  return x + y;
}

The above is a "normal" function. If you don't pass all the arguments you'll get unexpected results.

Now, if you want a function that adds 2 to any number, you could partially apply an argument to add, for example:

function add2(x) {
  return add(2, x);
}

But in JavaScript we have first class functions (objects that can be passed around), so a function can take functions as inputs and return other functions. This is where "currying" comes in handy. While "partial application" lets you fix function arguments, "currying" takes a function of many arguments and breaks it down into a function of a single argument that returns another function of one single argument until all the arguments have been evaluated, in order, and then returns the result. For example:

function add(x) {
  return function(y) {
    return x + y;
  }
}

Now you can create a function add2 by currying the function add:

var add2 = add(2);
add2(1); //=> 3

The normal function and the curried one have equivalent computations where:

add(1, 2) === add(1)(2)

This is what makes "several parentheses" possible.

In JavaScript "scope" and "closure" refer to functions but they're different concepts. A "scope" determines the reach/privacy of your variables while a "closure" lets you encapsulate code and carry it around. In the curried function above the variable x is kept in memory through closure because it's referenced inside the returned function object.

A particular limitation of "currying" is that you can't have functions of dynamic arity; the number of arguments must be fixed. This is not the case in the code you post where your sum function must be able to add a new number to the previous sum indefinitely.

Similarly to "currying" there's the idea of "generators"; a pattern to model sequences of lazy computation, in this case just adding a number to the previous sum on demand.

function sum(a) { // begin closure
  var sum = a; // kept in memory...
  function f(b) {
    sum += b; //...because you use it here
    return f;
  }
  f.toString = function() { return sum };
  return f;
} // end closure

A different (maybe more clear) way to express your code would be to return an object to chain the computations, where you can either add a new number to the previous sum, or get the total sum so far:

function add(a) {
  var sum = a;
  return {
    plus: function(b) {
      sum += b;
      return this;
    },
    sum: function() {
      return sum;
    }
  }
}

add(1).plus(2).plus(3).sum(); //=> 6

In your code the returned function f acts as plus and toString as sum which retrieves the value.



回答3:

  1. Line 01-13 defines the function sum within the global scope.
  2. Line 15 calls sum and changes scope to inside the function.
    1. The variables a and sum and the closure function f are all defined in the function's scope - with the sum variable hiding the function definition from the global scope.
    2. I'll skip over the toString bit here as its not important till later (when it gets very important).
    3. The function sum finally returns a reference to the closure function f to the global scope as an anonymous function (since f can only be referenced by name from within its containing function's scope).
  3. Back to line 15 - sum(1)(2) is the same as (sum(1))(2) and since sum(1) returns f then this can be reduced to (f)(2) or, more simply, f(2).
    1. Calling f(2) adds 2 to sum - sum is defined in two scopes: as a function in the global scope; and as a variable (currently assigned the value of 1) within that function which hides the definition from the global scope - so, in f, the sum variable is set to 1+2=3.
    2. Finally, in f, the function returns itself.
  4. Back, again, to line 15 - f(2) returns f (although the named function f cannot be referenced in the global scope and, again , is treated as an anonymous function)
  5. alert() is processed and the anonymous function (referred to as f) is converted to a string to be alerted; normally when alert() is called on a function it will display the source for the function (try commenting out Line 10 to see this). However, since f has a toString method (Line 10) then this is invoked and the value of sum (as defined in the function containing f) is returned and 3 is alerted.


回答4:

Chaining

Notice that:

  • The 4 occurences of f refer to the same function.
  • The first pair of brackets calls sum while the others call f.
  • sum returns f and f returns itself, in other words, whenever you write (), you're returning the same f function.

In summary:

sum(0)       // sum(0) -> f
sum(0)(1)    // sum(0), f(1) -> f
sum(0)(1)(2) // sum(0), f(1), f(2) -> f

Persistence

That being said, the main question is: how the state of the sum is able to persist along those function calls? This is where this famous "closure" thing comes in. I'm not going to talk about this concept in details, Google can help far better. In a few words, it's about the relationship between f and the sum variable. Indeed, from the moment they come to life, thanks to the first function call, they'll share the same private context for the rest of their existence. Consequently, every subsequent call consists in modifying the existing sum variable through f:

sum(0)       // var sum = 0
sum(0)(1)    // var sum = 0, sum += 1
sum(0)(1)(2) // var sum = 0, sum += 1, sum += 2

Result

Finally, toString is called automatically when a string is expected in place of f:

typeof(sum(1)(1))      // typeof(f) -> "function"
typeof(sum(1)(1) + '') // typeof(f + '') -> typeof('2' + '') -> "string"
                                                    ^
                                                    toString was called

Note that you could also use valueOf. It might be a bit more consistent since Function already owns a version of the toString method in order to get the function declaration itself.

Bonus

That's it, hope this explanation was clear enough. As a conclusion, here is a similar approach (to get the final result, just put an empty pair of brackets at the end of the queue):

function sum(a) {
    return function (b) {
        return arguments.length ? sum(a+b) : a;
    };
};

sum(1)(1)(1)(); // 3


回答5:

Let's step through the function line by line:

function sum(a) {

This part is pretty self-explanatory; we have a function named sum which accepts an argument a.

    var sum = a

Here we have a local variable called sum that is set to the value of the argument that is passed in.

    function f(b) {
        sum += b
        return f
    }

This is an inner function called f that accepts an argument called b. This b is then added to the value of sum from the outer scope (i.e., inside the scope of the function that is also called sum). After that, the function returns itself.

    f.toString = function() { return sum }

This is the fun part! When you normally console.log a function, it will just spit out the function's source. Here we are redefining the toString method to instead be a function that spits out the value of sum. This is why you end up seeing the running total that is displayed instead of the function's source even though what you are returning is still a function.

Finally we have:

    return f

So you basically have a function sum, returning a function that returns itself. The function sum basically sets everything up, but after calling sum(3), you then work with f, which you repeatedly call.

So the first time you call sum, you essentially get back this function:

function f(b) {
   sum += b; //value of sum is 3
   return f;
}

In this context, the value of sum will be the value of a that you passed into the initial call of the function sum. However, since the toString of f has been redefined, you only see the value 3. Then let's say you do sum(3)(4).

You get back, as before:

function f(b) {
   sum += b; //value of sum is 3
   return f;
}

But then you are actually calling f with an argument of 4 (basically f(4)). Since f is an inner function, it has full access to the scope of its parent function. This parent function (sum) is maintaining the the running total in a variable called sum, which is accessible to f. So when you now call f(4), you have b set to 4 and sum having a value of 3:

function f(b) { //b is 4
   sum += b; //value of sum is 3 + 4, which is 7
   return f;
}

So with each subsequent pair parentheses you are making repeated calls to the same f which is maintaining a running tally.

Another way is to think of sum as a kind of factory that can give you different f's, all of which keep their own running tallies (basically behaving like accumulators):

var firstSum = sum(4);
var secondSum = sum(2);

firstSum(5); //equivalent to sum(4)(5) returns 9
secondSum(2); //equivalent to sum(2)(2) returns 4


回答6:

There are 3 concepts being played here

  • closures (no scope).
  • functions are first class OBJECTS in javascript (allows for chaining f(a)(b)(c)). There's no need to save a handle to the function to call it later.

I'll give you a run-down and then add some extra explanations afterwards

function sum(a) {
  // when sum is called, sumHolder is created
  var sumHolder = a;
  // the function f is created and holds sumHolder (a closure on the parent environment)
  function f(b) {
    // do the addition
    sumHolder += b;
    // return a FUNCTION
    return f;
  }
  // change the functions default toString method (another closure)
  f.toString = function() {return sumHolder;}
  // return a FUNCTION
  return f
}
/*
 * ok let's explain this piece by piece
 * 
 * you call sum with a parameter
 *  - parameter is saved into sumHolder
 *  - a function is returned
 * 
 * you call the returned function f with another parameter
 * EXPLANATION: { sum(a) } returns f, so let's call f as this => {...}()
 *  - this private (priviledged) function adds whatever it's been passed
 *  - returns itself for re-execution, like a chain
 * 
 * when it all ends {{{{}(a)}(b)}(c)} the remainder is a FUNCTION OBJECT
 * this remainder is special in that it's toString() method has been changed
 *  so we can attempt to cast (juggle) it to string for (loose) comparison
 * 
 */

The concept behind closures is quite easy to understand but it's application make's your head spin until you get used to the idea that there is no function scope in javascript, there is closures and these are powerfull critters indeed

// this anonymous function has access to the global environment and window object
(function()
  {// start this context
    var manyVars, anotherFunc;
    function someFunc() {
      // has access to manyVars and anotherFunc
      // creates its own context
    };
    anotherFunc = function () {
      // has access to the same ENVIRONMENT
      // creates its own context
    };
  }// whatever is in these keys is context that is not destroyed and
  //  will exist within other functions declared inside
  //  those functions have closure on their parent's environment
  //  and each one generates a new context
)();

Functions are first class objects. What does this mean? I'm not sure myself but let me explain with some further examples:

// how about calling an anonymous function just as its created
// *cant do the next line due to a language constraint
// function(){}()
// how about a set of parens, this way the word "function" is not the first expression
(function(){}());
// the function was created, called and forgotten
// but the closure inside MAY STILL EXIST
function whatDoIReturn() {
  return function (){alert('this is legal');return 'somevalue';}();// and executed
}// returns 'somevalue'

Don't take this word for word. Go look for other people's code, check the Crockford and ask any and all questions that come up