There are three ways of creating objects in JavaScript:
- by simple Object creating
- by Factory function
- by Constructor function
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:
- Constructors vs Factory Methods
- Constructor function vs Factory functions
- Creation of Objects: Constructors or Static Factory Methods
So I’m asking for some simple practical cases.