javascript factory function code example

Example 1: factory function javascript

function createPerson(firstName, lastName) {
  return {
    firstName: this.firstName,
    lastName: this.lastName,
    getFullName: function () {
      return `${this.firstName} ${this.lastName}`
    }
  }
}

let user = createPerson('John', 'Doe');
console.log(user.getFullName()); // John Doe

Example 2: factory function vs constructor javascript

// constructor
function ConstructorCar () {}
ConstructorCar.prototype.drive = function () {
  console.log('Vroom!');
};

const car2 = new ConstructorCar();
console.log(car2.drive());

// factory
const proto = {
  drive () {
    console.log('Vroom!');
  }
};

const factoryCar = () => Object.create(proto);
const car3 = factoryCar();
console.log(car3.drive());

// class
class ClassCar {
  drive () {
    console.log('Vroom!');
  }
}
const car1 = new ClassCar();
console.log(car1.drive());