gpt4 book ai didi

Javascript 类与 Nodejs 中函数的 "List"

转载 作者:行者123 更新时间:2023-11-30 06:13:04 28 4
gpt4 key购买 nike

<分区>

我是编程新手,目前我想知道类与 NodeJ 中相关函数的简单“列表”相比有什么好处。

作为一个非常简单的例子,我想如果我使用类,我会创建一个这样的用户:

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');

第二种方式在我看来,它可以用更少的代码结束。甚至不必实例化类(class)。

假设我有一个 Node API,具有多个“用户”路由和 Controller 。我想每次调用用户路由/ Controller 时我都必须实例化用户类,对吗?作为初学者,这对我来说听起来不是“优化”的……但我肯定遗漏了一些东西……

谢谢你的帮助

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com