Home > Net >  Cannot read properties of undefined usding "This" in JavaScript class
Cannot read properties of undefined usding "This" in JavaScript class

Time:05-31

I'm using Node JS and ExpressJS to write my web server. I use JavaScript OOP fromfew time. I get an error running this class:

class myClass  {

  constructor(path) {
    this.path = path;
  }


      
    myFunction(){

      var fileControllerInstance = new FileController(this.path);

      fileControllerInstance.fileExist(function(fileExist) {
        if(fileExist){
          console.log("file exist");
          this.printLine("test");
        }
        else
          return false;
      });
        
    }


    printSTR(str){
      console.log(str);
    }


    
}

new myClass("filePath").myFunction();
module.exports = myClass;

Running this class I get an error on printSTR function. Error is the follow:

file exist
TypeError: Cannot read properties of undefined (reading 'printSTR')

Without this I get ReferenceError: printSTR is not defined. To solve my problem I need to create another class instance and to use that to call the function. Something like this:

new myClass("filePath").printSTR("test") instead to ``` this.printLine("test"); ```

Why using this my code not working? Thanks

CodePudding user response:

Inside the function(fileExist), this has a different value than outside. To inherit the value inside, you must bind the function:

fileControllerInstance.fileExist(function(fileExist) {
  ...
}.bind(this));

CodePudding user response:

You're calling this inside a callback. You can find this post useful to solve your issue.

Also you try to call printLine("test") but your method is printSTR(str)

  • Related