我是编程方面的新手,我目前想知道类与 NodeJ 中相关函数的简单“列表”的好处是什么。
作为非常简化的示例,我想如果我使用 Class,我会创建一个这样的用户:
class User {
constructor(email) {
this.email = email;
}
validateEmail() {
// whatever function that checks if this.email is valid
if (this.email === 'notValid') {
throw new Error();
}
return this;
}
create() {
this.validateEmail();
// whatever function that inserts user in the database
return user;
}
}
const newUser = new User('test@test.com');
const user = newUser.create();
我会用我称之为相关函数的“列表”来做这样的事情:
const validateEmail = email => {
// whatever function that checks if valid email
if (email === 'notValid') {
throw new Error();
}
return true;
};
const createUser = email => {
if (validateEmail(email)) {
// whatever function that inserts the user in the database
return user;
}
};
const user = createUser('test@test.com');
在我看来,第二种方式可以用更少的代码结束。甚至不必设置类。
假设我有一个节点 API,有多个“用户”路由和控制器。我想每次调用用户路由/控制器时我都必须实例化用户类,对吗?作为初学者,这对我来说听起来并不“优化”......但我肯定错过了一些东西......
动漫人物
相关分类