0

I have followed a lot of tutorials and books.. It seems like that sometimes the author itself refrains from explaining the difference between the two and when to use one or how is one better than another. I still do not understand the basic difference of their existence in modern javascript.

Factory Function:

function greet(title, name) {
  return sayHello = {
    title,
    name,
    greetings: function() {
      return 'hello ' + title + ' ' + name;
    }
  }
}

var person1 = greet('Mr', 'Alex');
person1.greetings();

Constructor:

function Greet(title, name) {
  this.title = title,
  this.name = name,
  this.greetings = function() {
    return 'hello ' + title + ' ' + name;
  }
}

var person1 = new Greet('Mr', 'Alex');
person1.greetings();

So what else is the difference other than using 'new' in constructor? Some people argue that factory function returns an object. Constructor does that too.I still cannot wrap my head around these two and then there is another called Class.

So basically the only difference is the 'new' keyword used for constructor? And either one can be used? As I understand it's like two ways of doing the same thing in JS, am I correct?

Jaz
  • 135
  • 4
  • 16
  • 1
    Your first code implicitly creates a global variable. Don't do that. (Also try to indent code properly) – CertainPerformance Sep 29 '18 at 09:00
  • So basically the only difference is the 'new' keyword used for constructor? And either one can be used? As I understand it's like two ways of doing the same thing in JS, am I correct? – Jaz Sep 29 '18 at 09:27
  • @CertainPerformance I m assigning it to a variable. What is the correct way of doing it? thanks – Jaz Sep 29 '18 at 09:40
  • 1
    @Jaz Drop the `sayHello =`. – Bergi Sep 29 '18 at 10:33
  • 1
    A constructor function called wit `new` constructs a new *instance*. The object you are creating *inherits* from `Greet.prototype`. You probably will later learn how to use this. – Bergi Sep 29 '18 at 10:35
  • @Bergi the accepted answer has also assigned a variable to objects in factory function example [Constructor function vs Factory functions](https://stackoverflow.com/questions/8698726/constructor-function-vs-factory-functions) Can you confirm if it was wrongly used as well? I am a bit confused. Thank you – Jaz Oct 01 '18 at 09:24
  • 1
    @Jaz You mean the local variable `obj` inside the factory function? Yes, it's usually not necessary and can be omitted, but sometimes you will need it. – Bergi Oct 01 '18 at 12:46

0 Answers0