我正在使用 Node JS 和 ExpressJS 來撰寫我的 Web 服務器。我很少使用 JavaScript OOP。運行此類時出現錯誤:
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;
運行此類我在 printSTR 函式上遇到錯誤。錯誤如下:
file exist
TypeError: Cannot read properties of undefined (reading 'printSTR')
沒有this我得到ReferenceError: printSTR is not defined。為了解決我的問題,我需要創建另一個類實體并使用它來呼叫函式。像這樣的東西:
new myClass("filePath").printSTR("test") instead to ``` this.printLine("test"); ```
為什么使用this我的代碼不起作用?謝謝
uj5u.com熱心網友回復:
內部function(fileExist),this的值與外部不同。要繼承里面的值,你必須系結函式:
fileControllerInstance.fileExist(function(fileExist) {
...
}.bind(this));
uj5u.com熱心網友回復:
您在this回呼中呼叫。您會發現這篇文章對解決您的問題很有用。
你也試著打電話printLine("test"),但你的方法是printSTR(str)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483874.html
上一篇:一鍵隨機播放多個選擇選單選項
下一篇:PythonOOP-更改類文本
