Estoy usando Node JS y ExpressJS para escribir mi servidor web. Uso JavaScript OOP desde hace poco tiempo. Me sale un error al ejecutar esta clase:
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;
Al ejecutar esta clase, aparece un error en la función printSTR. El error es el siguiente:
file exist TypeError: Cannot read properties of undefined (reading 'printSTR')
Sin this
obtengo ReferenceError: printSTR is not defined
. Para resolver mi problema, necesito crear otra instancia de clase y usarla para llamar a la función. Algo como esto:
new myClass("filePath").printSTR("test") instead to ``` this.printLine("test"); ```
¿Por qué usar this
código no funciona? Gracias
Dentro de la function(fileExist)
, this
tiene un valor diferente que fuera. Para heredar el valor interior, debe vincular la función:
fileControllerInstance.fileExist(function(fileExist) { ... }.bind(this));
Estás llamando a this
dentro de una devolución de llamada. Puede encontrar esta publicación útil para resolver su problema.
También intenta llamar a printLine("test")
pero su método es printSTR(str)