所以我参加了关于 JS 的 udemy 课程,在制作应用程序期间,他编写了如下代码。当我开始运行代码时,会出现一个错误,提示“TypeError:this.validate 不是函数”。我尝试了不同的导出 User 的方法,有时它告诉我它无法将 User 读取为我想要的构造函数。在过去的 4 个小时里,我一直在做这个,但我仍然无法弄清楚它是如何工作的。其他文件需要整个文件。当在这些其他文件上时,我创建了一个对象的实例,如下所示。尽管当我调用 pushError 函数时无法访问数组的 .push 方法(弹出错误消息),但它仍然有效
const User = require('../models/User.js')
let user = new User(req.body);
//I can then run the .validate function
user.validate();
//But in that function another error raises that says that the
//"push cannot be accessed in undefined"
//And it leads me to think that during the construction the
//empty list becomes undefined????
let User = function(data) {{
this.username = data.username;
this.mail = data.email;
this.password = data.password;
this.errors = [];
}
}
User.prototype.validate = function(){
if(this.username.replace(" ","") == ""){pushError("Username")}
if(this.password == ""){pushError("Password")}
if(this.mail.replace(" ","") == ""){pushError("Email")}
}
User.prototype.register = ()=>{
//Step #1: Validate user Data
this.validate();
//Step #2:If validated store data to DB
}
function pushError(str){
this.errors.push(`You must provide a valid ${str}.`);
};
module.exports = User;
如果您通读所有这些,谢谢!