在 JavaScript 中,它更多的是关于约定。私有属性或方法首先使用下划线定义,例如_private. 使用一些助手,您可以轻松地制作课程。我发现这个设置很简单,你只需要一个inherits扩展类的助手,而不是使用多个参数,你传入一个对象props并简单地在继承的类上调用“super” arguments。例如,使用模块模式:
Function.prototype.inherits = function(parent) {
  this.prototype = Object.create(parent.prototype);
};
var Person = (function PersonClass() {
  function Person(props) {
    this.name = props.name || 'unnamed';
    this.age = props.age || 0;
  }
  Person.prototype = {
    say: function() {
      return 'My name is '+ this.name +'. I am '+ this.age +' years old.';
    }
  };
  return Person;
}());
var Student = (function StudentClass(_super) {
  Student.inherits(_super);      
  function Student(props) {
    _super.apply(this, arguments);
    this.grade = props.grade || 'untested';
  }
  Student.prototype.say = function() {
    return 'My grade is '+ this.grade +'.'; 
  };
  return Student;
}(Person));
var john = new Student({
  name: 'John',
  age: 25,
  grade: 'A+'
});
console.log(JSON.stringify(john)); //=> {"name":"John","age":25,"grade":"A+"}
console.log(john.say()); //=> "My grade is A+"
关于私有变量“问题”,只需遵守实例属性的约定,并在需要其他所有私有内容时使用闭包。