Javascript - Object Creation Factory Pattern


The factory pattern handles the process of creating specific objects.

You create functions to encapsulate the creation of objects with specific interfaces.

function createPerson(name, age, job){
    var o = new Object(); = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
    return o;

var person1 = createPerson("First", 29, "writer");
var person2 = createPerson("Tom", 27, "Doctor");

Here, the function createPerson() accepts arguments with which to build an object to represent a Person.

The function can be called any number of times with different arguments.

It returns an object that has three properties and one method.