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:
function PersonType(name) {
this.name = name;
}
PersonType.prototype.sayName = function() {
console.log(this.name);
};
let person = new PersonType("Nicholas");
person.sayName(); // outputs "Nicholas"
console.log(person instanceof PersonType); // true
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.