Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

102
Views
Cannot read properties of undefined usding "This" in JavaScript class

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

8 months ago · Santiago Trujillo
2 answers
Answer question

0

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));
8 months ago · Santiago Trujillo Report

0

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)

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.