Class-Like Structures in ECMAScript 5

In ECMAScript 5 and earlier, JavaScript had no classes. The closest equivalent to a class was creating a constructor and then assigning methods to the constructor’s prototype, an approach typically called creating a custom type. For example:

  1. function PersonType(name) {
  2. this.name = name;
  3. }
  4. PersonType.prototype.sayName = function() {
  5. console.log(this.name);
  6. };
  7. let person = new PersonType("Nicholas");
  8. person.sayName(); // outputs "Nicholas"
  9. console.log(person instanceof PersonType); // true
  10. console.log(person instanceof Object); // true

In this code, PersonType is a constructor function that creates an instance with a single property called name. The sayName() method is assigned to the prototype so the same function is shared by all instances of the PersonType object. Then, a new instance of PersonType is created via the new operator. The resulting person object is considered an instance of PersonType and of Object through prototypal inheritance.

This basic pattern underlies a lot of the class-mimicking JavaScript libraries, and that’s where ECMAScript 6 classes start.