Gareth Redfern developer, cyclist & coffee lover

Factory Function To Create An Object In Javascript

Posted by Gareth Redfern
Category: javascript

Use a constructor function that returns an object. You can then create multiple people by passing in the first and last name arguments the createPerson function.

// Factory Function To Create An Object
var createPerson = function(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    sayHi: function() {
      return "Hi there";
    }
  }
}
var johnDoe = createPerson("John", "Doe");
var janeDoe = createPerson("Jane", "Doe");