Javascript 什么';s表示Node.js中状态的常用模式

Javascript 什么';s表示Node.js中状态的常用模式,javascript,node.js,functional-programming,Javascript,Node.js,Functional Programming,例如,在经典的面向对象编程中,我可能有一个班级,它有一个表示学生的字符串数组(不是理想的数据结构,只是为了说明)。它可能看起来像这样 class School { String name; String[] students; } 然后我可以举例说明一些不同的学校,每个学校有不同的名字和不同的学生。这个概念如何转化为Node.js?如果我有一个学校模块,那么整个应用程序将共享一个实例。我最初的想法是将每个学校表示为JSON对象,并基本上传递JSON,通常我会传递学校的一个实例。

例如,在经典的面向对象编程中,我可能有一个班级,它有一个表示学生的字符串数组(不是理想的数据结构,只是为了说明)。它可能看起来像这样

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

构造函数和实例:

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

如果状态对外隐藏(即受保护的属性),则可以执行以下操作:

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