Parasitic Constructor Pattern

Description

The parasitic constructor pattern is to create a constructor that simply wraps the creation and return of another object.

Example


function Person(name, age, job){// www  . j ava2 s. co m
   var o = new Object();
   o.name = name;
   o.age = age;
   o.job = job;
   o.sayName = function(){
      console.log(this.name);
   };
   return o;
}

var friend = new Person("XML", 29, "markup");
friend.sayName();  //"XML"

The code above generates the following result.

Note

The function is called as a constructor, using the new operator.

Example 2

You create a special array that has an extra method.


function MyArray(){/*  w ww.j av a 2s. c  o  m*/
    var values = new Array();
    values.push.apply(values, arguments);
    
    values.toMyString = function(){
       return "["+this.join(",")+"]";
    };
    values.count = function(){
       return this.length;
    };
    return values;
}
var colors = new MyArray("A", "B", "C");
console.log(colors.toMyString());
console.log(colors.count());

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