Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
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

over 4 years 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));
over 4 years 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)

over 4 years 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 vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda