Constructors and Prototypes
Object-oriented programming (OOP) can be thought of as describing the properties and behaviour of a noun in a blueprint, which is used to create instances of an object. The blueprint is defined as a Constructor — a function that identifies a class of objects and begins with a capital letter. New objects are created by calling a Constructor with the keyword
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
The Book constructor specifies two properties,
author, and one method,
listing. Defining a method in a constructor ensures that all instances of the Object have the same method, but it also results in duplication of the method in the memory stack for every instance of the Object. If I made 1000 instances of Book, there would be 1000 instances of the listing method, even though it is only defined once, and is the same for every object.
Memory stack of objects with instance methods:
A Prototype is a property that is shared by all instances of an object. When the constructor for an object is called for the first time, all the object’s properties are loaded onto the memory stack as well as the object’s Prototype. All subsequent instances of that object include a pointer to the same Prototype, and they pass in a pointer to themselves as
this whenever they call a method from the Prototype.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Memory stack of object with prototypes:
Reduced memory consumption is one advantage of keeping a reference to a prototype instead of a complete copy. Another advantage is that if additions are made to the Prototype, the changes will be extended to all instances.