Parasitic Constructor Pattern


The parasitic constructor pattern is typically a fallback when the other patterns fail. The basic idea of this pattern is to create a constructor that simply wraps the creation and return of another object while looking like a typical constructor. Here's an example:

			
			
			
			

In this example, the Person constructor creates a new object, initializes it with properties and methods, and then returns the object. This is exactly the same as the factory pattern except that the function is called as a constructor, using the new operator. When a constructor doesn't return a value, it returns the new object instance by default. Adding a return statement at the end of a constructor allows you to override the value that is returned when the constructor is called. This pattern allows you to create constructors for objects that may not be possible otherwise. For example, you may want to create a special array that has an extra method. Since you don't have direct access to the Array constructor, this pattern works:

			
			
			
			

In this example, a constructor called SpecialArray is created. In the constructor, a new array is created and initialized using the push() method (which has all of the constructor arguments passed in). Then a method called toPipedString() is added to the instance, which simply outputs the array values as a pipe - delimited list. The last step is to return the array as the function value. Once that is complete, the SpecialArray constructor can be called, passing in the initial values for the array, and toPipedString() can be called. A few important things to note about this pattern: There is no relationship between the returned object and the constructor or the constructor's prototype; the object exists just as if it were created outside of a constructor. Therefore, you cannot rely on the instanceof operator to indicate the object type. Due to these issues, this pattern should not be used when other patterns work.