-1

Here is a closure example from the wikipedia article

function startAt(x)
   function incrementBy(y)
       return x + y
   return incrementBy

variable closure1 = startAt(1)
variable closure2 = startAt(5)

According to the article

Invoking closure1(3) will return 4, while invoking closure2(3) will return 8.

What is going on behind the scenes?

  1. Why would not this code throw any kind of error in a real programming language? incrementBy requires a second variable to do the sum, doesn't it?

  2. When we call closure() with an argument, am I right that it being assigned to the y within incrementBy scope?

  3. Am I right that closure2 two is binded to a record different from the record that closure1 binded to?

Rotkiv
  • 1,051
  • 2
  • 13
  • 33
  • Does this example help: http://stackoverflow.com/questions/18234491/two-sets-of-parentheses-after-function-call/18234552#18234552 ? The JavaScript closure example is pretty much identical to the closure in your question. Aside from the fact that the inner function is anonymous instead of named `incrementBy`. – Paul Jun 10 '16 at 17:09
  • You could also read this: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work . I would say it is a duplicate except that your question seems to be language agnostic. – Paul Jun 10 '16 at 17:17

1 Answers1

0

Why would not this code throw any kind of error in a real programming language? incrementBy requires a second variable to do the sum, doesn't it?

Why would it throw an error? Yes incrementBy uses two variables x and y, but they're both defined. x was defined to be 5 when startAt(5) was called. y was defined to be 3 when closure2(3) was called.

When we call closure() with an argument, am I right that it being assigned to the y within incrementBy scope?

Yes, you are correct that it is being signed to y within a incrementBy, but note that there are multiple functions called incrementBy. One gets created every time startAt is called. In your code there are two separate incrementBy functions created by the two calls to startAt, each of which has its own context which contains its own x in scope.

Am I right that closure2 two is binded to a record different from the record that closure1 binded to?

Yes, closure2 and closure1 are two separate functions, which are both copies of incrementBy, but in different contexts.

Paul
  • 139,544
  • 27
  • 275
  • 264