Deadpool
Deadpool

Reputation: 8240

Simple Object vs. Factory vs. Constructor - Practical Example

There are three ways of creating objects in JavaScript:

  1. by simple Object creating
  2. by Factory function
  3. by Constructor function

  1. Simple Object Creation:

    var ronaldo = {
        name: "Ronaldo",
        age: "35",
        quote: "Hi I am Ronaldo", 
        salary: function(x){ return x+2500; }
    };
    
  2. 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);
    
  3. 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.

Upvotes: 8

Views: 2403

Answers (1)

Max Heiber
Max Heiber

Reputation: 15502

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

Upvotes: 3

Related Questions