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?