I'm playing around with ES6 classes and my eventual goal is to understand the difference between classes vs constructor functions vs factory functions. My current understanding is that constructor functions and classes are basically using the same design pattern, classes just being the new syntax for the constructor functions. Based on this assumption, I'm trying to create some examples that display the contrast between class/constructor functions and factory functions.
With the examples below I aim to return new objects and some methods that are inherited.
My first example is rather straightforward with the class syntax.
Example #1: Classes
class Person {
constructor(name, age, location, occupation) {
this.name = name;
this.age = age;
this.location = location;
this.occupation = occupation;
}
printDescription() {
console.log(`My name is ${this.name} and I'm ${this.age} years old. I live in ${this.location} and I work as a ${this.occupation}.`);
}
}
const firstUser = new Person('Tom', 30, 'Sydney', 'Teacher');
firstUser.printDescription();
With the second example, I'm trying to replicate the first one with a different approach but I'm not sure if this is factory constructor or a factory function.
Example #2: ?
function PersonMaker (name, age, location, occupation) {
let person = {name, age, location, occupation};
person.printDetails = () => {
console.log(`My name is ${name} and I'm ${age} years old. I live in ${location} and I work as a ${occupation}.`);
};
return person;
}
const secondUser = PersonMaker('Johnny', 25, 'London', 'Driver');
secondUser.printDetails();
I need to clarify the pattern used in the second example and if it's not a factory function, how I could turn it into one?