Objects can contain both methods and properties. Methods are functions called when we interact with an object, and properties are data associated with an object.
The Prototype Pattern is a technique for extending objects by giving the current objects new properties and methods. Although it has been a design pattern for many years, it has only recently become popular.
By using the prototype chain, we can avoid duplicating methods and properties, which saves memory by allowing us to access properties that aren't directly defined on the object itself.
The prototype chain is very useful because it allows you to create an object which inherits from another object, without having to copy all its properties and methods into your own object.
The primary goal of this pattern is to facilitate the creation of objects that can serve as blueprints for all constructor-created objects. It accomplishes this through a process known as prototypal inheritance.
To better understand, let's use the example of a car and begin implementing Factory Pattern and Prototype Pattern and difference between them.
- With Factory Pattern
Imagine using a Car factory function to produce numerous cars.
This way, we can easily create many car objects with the same properties.
If you want to know more about factory pattern read out this blog.
- With Prototype pattern
To distribute these methods among numerous car objects, we can use the prototype pattern.
- Method 1
Car.prototype<method> = function()..., we define a car's methods in our example code. Now that the
new keyword has been instantiated on some cars, we are looking at all the instances. According to the arguments that the caller passed in, we set their
The instances we're looking at are actually making reference to the same
accelerate methods that we defined in the prototype, as shown!
- Method 2
We can easily share properties, like drive and acceleration in this case, among the numerous instances, thanks to ES6 classes.
We can avoid duplicating methods and properties by using the prototype chain, which also enables us to access properties that aren't directly defined on the object itself. This helps conserve memory.
I hope you found this useful. Please keep an eye out for more in the future.
If you have any queries, then feel free to connect with me on my LinkedIn profile - Shubham Dutta. Please get in touch with me if you have any inquiries.