3

Can someone tell me what is difference between:

function Customer(name, age) {
    this.Name = name;
    this.Age = age;
}

var cust1 = new Customer('Your Name', 20);
var name1 = cust1.Name;
var age1 = cust1.Age;

and:

function Customer() {
    return {
        Name: 'Your Name',
        Age: 20
    }
};

var cust2 = Customer();
var name2 = cust2.Name;
var age2 = cust2.Age;

It produces the same output, after all, but the mechanics are different and I am not sure why.

what's the purpose of "new" in the first one though i could just do this:

var cust1 = Customer('Your Name', 20);
var name1 = cust1.Name;
var age1 = cust1.Age;
  • 6
    Well, no. 1 is a constructor function while no. 2 returns an evaluated object literal. Try `Object.getPrototypeOf(...)` on both and you will find a difference. The question is interesting and deserves a good answer as both patterns can serve a different purpose. – le_m Mar 18 '17 at 19:07
  • sorry, i updated the my post. – Jed Monsanto Mar 18 '17 at 19:12
  • 1
    This is not a duplicate - the question is about constructor vs. factory functions, not constructor vs. object literal, and the answers to the existing questions don't answer this. – Stuart Mar 18 '17 at 19:49

2 Answers2

3

The first uses a constructor, the second a factory function.

Constructors are functions that you invoke with the new keyword. Doing so allocates a new object for you and make this a reference to this new object so you can easily mutate it. Constructors are basically syntax sugar that mimics other OOP languages construct to create new objects.

Factories are simple functions that return a plain object. You are in charge of allocating the new object yourself and returning it.

The result is exactly the same at the difference that you can't use instanceof with objects created via a factory function.

Both have pros and cons that get beyond the subject of this question: Constructors vs Factory Methods.

Community
  • 1
  • 1
ngryman
  • 7,112
  • 2
  • 26
  • 23
0

The output is equal (more less) but the code behaves in two different ways

In the first case the 'function' is used as a constructor for a new Js Object
Differently in the second case the 'function' just returns an object.

There isn't a real difference between the two methods but the first is more used and recommended

console.log() the two results in:
constructor: Customer { Name: 'Your Name', Age: 20 }
return obj: { Name: 'Your Name', Age: 20 }