Instantiation patterns refer to the way instances of objects are created. There are different instantiation patterns and these patterns have different opinions of how a class creates a new instance of an object. This article will cover pseudoclassical instantiation.
All instantiation patterns have the same following functionality:
Creates a new object.
Creates properties which are methods for the newly created object.
To create a new instance in pseudoclassical style, we must start with a class function. The class is the constructor function that creates instances of new objects that inherits properties from the class prototype. We can metaphorically think of this class as a carpentry school. This school has all the knowledge that students need to build things.
For example, here we have a class called BuildDiningSet. This function has a prototype property which contains methods for building furniture and other methods.
class BuildDiningSet {
constructor(chair, table) {
this.chair = {};
this.table = {};
this.chairCount = 0;
this.tableCount = 0;
}
}
As a result of an affiliation with the school, the students that go to that school will have inherited the knowledge of building different things upon graduation. Thus, as a result of invoking our class, we create new instances that will inherit the prototypes of our class.
The properties and methods are defined on the prototype property on the objects' class, not the object instances themselves. Each new instance refers back to the prototypal chain to access the prototype property of its' class.
BuildDiningSet.prototype.makeChair = chairType => {
this.chairCount++;
this.chair[chairType] = chairType;
},
BuildDiningSet.prototype.makeTable = tableType => {
this.tableCount++;
this.table[tableType] = tableType;
};
Now that our class has methods on its' prototype, we are ready to create new instances. To create a new instance with must use the "new" keyword. Our graduating students now know how to build tables and chairs.
const carpenter1 = new BuildDiningSet(tallChairs, roundTable);
carpenter1.makeChair();
carpenter1.makeTable();
Now we have a graduating student called carpenter1 that knows how to build tables and chairs. When the graduate goes to work he refers back to what he learned in school to perform the function.
When using the new keyword, it binds the keyword this to the new object being created and thus gives the new object all the properties specified in the class.
Pseudo classical instantiation is the most advanced method of object creation. With the use of syntactical sugar, it makes it so you don't have to do as much code writing as you would when using other instantiation styles.
Top comments (0)