Factory Pattern

Description

The factory pattern uses functions to encapsulate the creation of objects with specific interfaces.

Example


function createPerson(name, age, job){/*  w ww.ja v a  2 s  . c o m*/
   var o = new Object();
   o.name = name;
   o.age = age;
   o.job = job;
   o.sayName = function(){
         console.log(this.name);
   };
   return o;
}

var person1 = createPerson("XML", 29, "Mark up");
var person2 = createPerson("CSS", 27, "Style");
console.log(person1.name);
console.log(person1.age);
console.log(person1.job);
person1.sayName();

console.log(person2.name);
console.log(person2.age);
console.log(person2.job);
person2.sayName();

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions