0

I always thought that these callbacks had their own scope. What's going on here?

Eton_file_sync.prototype.add_file_listener = function(filename){
    //use chokidar to make a watcher for the filename
    var watcher = this.chokidar.watch(filename, {
        ignored: /[\/\\]\./,
        persistent: true
    });
    var some_variable = 1;
    watcher.on('change', function(path) {
        console.log ('File', path, 'has been changed');
        console.log (some_variable);
    });
};

when calling it by changing the file, why does the output of some_variable actually work?

File buffercont.asc has been changed
1
zedjay72
  • 177
  • 2
  • 10
  • 1
    Related: [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) Functions do have their own scope. Their scope is just also linked to the scopes of functions that they're embedded within, in a chain up to the global scope of the program. – Jonathan Lonowski Jul 07 '15 at 00:36

1 Answers1

1

They do have their own scope. If you define the value of that variable from within the event handler callback, you'd only be defining the value inside of that scope, but it would not affect the parent scope.

var some_variable = 1;
console.log(some_variable); // prints "1"
var callback = function() {
    var some_variable = 5;
    console.log (some_variable); // prints "5"
};
callback();
console.log(some_variable); // prints "1"

Notice in the above sample that defining the variable inside the function did not change it outside the function. Each function carries with it a scope chain, the same scope chain that it is created within. You can always access variables higher up in the chain unless they've been overridden further down the chain like in the above example.

CatDadCode
  • 58,507
  • 61
  • 212
  • 318