zedjay72
zedjay72

Reputation: 177

Why does this node.js callback work?

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

Upvotes: 0

Views: 63

Answers (1)

ChevCast
ChevCast

Reputation: 59244

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.

Upvotes: 1

Related Questions