例如,在经典的面向对象编程中,我可能有一个 School 类,它有一个代表学生的字符串数组(不是理想的数据结构,但仅用于说明目的)。它可能看起来像这样
class School {
String name;
String[] students;
}
然后我可以实例化一堆不同的学校,每个学校都有不同的名字和不同的学生。这个概念如何转化为 Node.js?如果我有一个 School 模块,那么单个实例将在整个应用程序中共享。我最初的想法是将每所学校表示为 JSON 对象,并基本上传递 JSON,而我通常会传递 School 的一个实例。这是正确的想法吗?是否有替代方法?
最佳答案
如果状态应该对外部隐藏(即 protected 属性),您可以这样做:
SchoolFactory = {
create: function(name, students) {
students = students || [];
// return the accessor methods
return {
getName: function() {
return name;
},
addStudent: function(student) {
students.push(student);
}
// add more methods if you need to
}
}
}
var school = SchoolFactory.create('Hogwarts');
console.log(school); // will not display the name or students
school.addStudent('Harry');
关于javascript - 在 Node.js 中表示状态的普遍接受的模式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671239/