什么是在Node.js中表示状态的普遍接受模式

例如,在经典的面向对象的编程中,我可能有一个class级学校有一个代表学生的string数组(不是理想的数据结构,但仅用于说明目的)。 它可能看起来像这样

class School { String name; String[] students; } 

然后,我可以实例化一堆不同名称,不同学校的学校。 这个概念如何转化为Node.js? 如果我有一个学校模块,而不是单个实例在整个应用程序中共享。 我最初的想法是把每个学校都当作JSON对象,基本上绕过JSON,我通常会绕过一个学校的实例。 这是正确的想法,是否有其他方法?

构造函数和实例:

 function School(name, students) { this.name = name; this.students = students || []; }; School.prototype.enroll = function (student) { if (!~this.students.indexOf(student)) { this.students.push(student); } else { throw new Error("Student '" + student + "' already enrolled in " + this.name); } }; var s = new School("Lakewood"); console.log(s.name); console.log(s.students); s.enroll("Me"); console.log(s.students); 

如果国家应该从外部隐藏(即受保护的属性),你可以做这样的事情:

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

我没有任何模式…但是如果你喜欢这些模块…你可以申报一个学校模块,并且有一个学校课程出口。 单个实例将不会被共享,因为您将实例化类