javascriptnode.jsscope

Variable scope in callback function


I ran into a problem with my JavaScript code.

I have a class MyClass and added function myFunction to its prototype.

MyClass.prototype.myFunction = function(file){
    if(some condition){
       fs.exists("./" + file, function(exists){
           if(exists)
               console.log(this.someValue);
               /* lot of other code */
           else
               /* do something else */
    });
    }else{
        /* do something */
    }
}

My problem is the scoping of this.someValue (as an example I want to just print it). Every time exists equals true the console logs undefined but it is not. If I would print it outside of fs.exists() then it has a value so I guess it is a scoping problem.

How can I access this.someValue in this sample?


Solution

  • As this - is keyword that is defined by scope of function and responds to owner or caller of a function. So you might store its pointer in another variable:

    MyClass.prototype.myFunction = function(file) {
      if(some condition) {
        var self = this; // create variable with pointer to 'this'
        fs.exists("./" + file, function(exists) {
          if(exists) {
            console.log(self.someValue); // we can access it to parent scope variables
            /* lot of other code */
          } else {
            /* do something else */
          }
        });
      } else {
        /* do something */
      }
    }
    

    As well check out this brilliant topic: How does the "this" keyword work?