There are three ways of creating objects in JavaScript:
Simple Object Creation:
var ronaldo = {
name: "Ronaldo",
age: "35",
quote: "Hi I am Ronaldo",
salary: function(x){ return x+2500; }
};
Factory Function:
function human(x,y,z,i){
return{
name: x,
age: y,
quote: z,
salary: function(i){ return i+2500; }
}
};
var Zini = human('Zenidan','41','I am Zidane',7500);
Constructor Function:
var human = function(x,y,z,i){
this.name = x,
this.age = y,
this.quote = z,
this.salary = function(i){ return i+2500; }
};
var Lampd = new human('Frank Lampard','39','I am Frank J Lampard',5500);
Can someone provide simple illustrations of when to use which of these methods to create objects in simple terms, so that a naive can also understand?
I went through the following links, but it’s a bit complicated to understand:
So I’m asking for some simple practical cases.
Factory methods promote the idea of coding using Interface then implementation which results in more flexible code, but constructor ties your code to a particular implementation. On the other hand by using constructor you tightly any client (who uses that class) to the class itself.
A factory constructor is a constructor that can be used when you don't necessarily want a constructor to create a new instance of your class. This might be useful if you hold instances of your class in memory and don't want to create a new one each time (or if the operation of creating an instance is costly).
The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
Factory functions are mainly used when the user wants to initialize the object of a class multiple times with some assigned value or static values. It makes the process easy since we just have to call this function and retrieve the new object created.
Use simple objects for data: when all you need is a bundle of key/value pairs.
In your example of a simple object, you have more than just data: the salary
method adds behavior to the object. If you're going to end up with many objects like that, it's better for performance and maintainability to have just one salary
method that is shared between all of the objects, rather than each object having its own salary
method. A way to share a method among many objects is to put the method on a prototype of the objects.
You can use a constructor function when you need to create an object that is an instance of a prototype. This is a good place to read about that, but it's a little dense: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
The MDN link above also demonstrates ECMAScript 2015 class
syntax, which is an alternative to constructor functions.
Update: See Dave Newton's comment for a good example of when to use a factory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With