在JavaScript中,“model”通常指的是数据模型,它是应用程序中数据和业务逻辑的主要载体。数据模型用于定义数据的结构、操作、约束和关系,是MVC(Model-View-Controller)架构模式的核心部分。
class UserModel {
constructor(name, email) {
this.name = name;
this.email = email;
}
// 数据验证
validate() {
if (!this.name || !this.email) {
throw new Error('Name and email are required.');
}
if (!this.email.includes('@')) {
throw new Error('Invalid email format.');
}
}
// 更新用户信息
updateName(newName) {
this.name = newName;
}
// 获取用户信息
getUserInfo() {
return { name: this.name, email: this.email };
}
}
// 使用模型
const user = new UserModel('John Doe', 'john@example.com');
user.validate();
console.log(user.getUserInfo());
user.updateName('Jane Doe');
console.log(user.getUserInfo());
在实际应用中,模型可能会更加复杂,包含与数据库的交互、更复杂的业务逻辑等。
没有搜到相关的文章