Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

101
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.