1

I try to learn javascript and therefore I tried the following code:

function repeat(n, action) {
    for (var i = 0; i < n; i++) {
        action();
    }
}
function benchmark() {
    var start = [], end = [], timings = [];
    repeat(1000, function() {
        start.push(Date.now());
        // Repeat something
        end.push(Date.now());
    });

    for (var i = 0; i < end.length; i++) {
        timings[i] = end[i] - start[i];
    }

    return timings;
}

My Question now: Why can I access start and end in my callback? As I understood the scope changed from benchmark to repeat. Is the callback a closure or is a closure onle a defined named function in another function?

Thanks!

Gerrit
  • 2,515
  • 5
  • 38
  • 63

3 Answers3

0

In short - your callback is nested inside benchmark which means it has access to the variables within the closure of benchmark. repeat is not nested within benchmark and thus does not have access to the variables in the closure of benchmark.

kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
  • But when I would access a variable with "this" in the closure, then the scope changed? – Gerrit Feb 07 '14 at 10:49
  • `this` refers to the immediate function in which it is used - thereby `this` used in first line of `benchmark` would not refer to the same as `this`used in the first line of `repeat`. – kaspermoerch Feb 07 '14 at 11:45
  • But why would this.startin benchmark() not points to the same as var start = []; – Gerrit Feb 07 '14 at 12:05
  • 1
    `this` is the object corresponding to the function `benchmark` and would not be accesible to inner functions in `benchmark` where as a variable declared inside `benchmark` like e.g. `var start = 'something'` would be accesible inside an inner function. – kaspermoerch Feb 07 '14 at 13:10
0

To understand that you have to understand the concept of closure.

Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function's lexical environment (i.e., the set of available variables) at the time when the closure was created

In your case, the callback which is invoked in repeat (action) is a closure and in it's lexical environment you have start, end, timings and all the available global variables.

Rui
  • 4,847
  • 3
  • 29
  • 35
0

But when I would access a variable with "this" in the closure, then the scope changed? And what happen if I initialize via this.start = []; an array in the first line of repeat function?

Gerrit
  • 2,515
  • 5
  • 38
  • 63