Simple "Class" Instantiation, the alternative solution.

Intro

JavaScript offer varies ways to create an instance of an Object. Take Array for example, we can get an instance of Array by doing these ways:

//object literal var a1 = [1,2,3]; //with the "new" operator var a2 = new Array(1,2,3); //without the "new" operator" var a3 = Array(1,2,3); a1.toString() == a2.toString(); //true a2.toString() == a3.toString(); //true a1.toString() == a3.toString(); //true

One thing interesting is that we can get an instance of an Array object without using the new operator. For varies kinds of different reason, some people would like to apply the same feature to their customized constructor Class, and we do have solutions for that.

Simple "Class" Instantiation

Before you get start with my article, please read this article written by John Resig : Simple "Class" Instantiation, whcih shows a simple but very inspiring way to construct an instance of JavaScript "Class".

In John's solution, he suggested that you need to implement a method named init for each JavaScript Class so that you can use his function makeClass() to do the work for you.

Finally, the last bit. Since we need to make the construction phase of the class generic, we defer that to an 'init' function property instead (Prototype uses 'initialize' instead, I like short words).

The tweak

If neither the function makeClass nor the method init is not an option for you, you may still try to add few lines into your constructor to get something similar.

Before

function User(firstName,lastName){ this.setName( firstName + ' ' + lastName ); }

After

function User(firstName,lastName){ if (!(this instanceof clz )) { var fn = function(clz) { clz.apply(this,clz.arguments) } fn.prototype = clz.prototype; return new fn(clz); } this.setName( firstName + ' ' + lastName ); }

or we can do this

and more...

Let's move some codes out of the constructor so that we can reuse them.

function makeInstance(clz){ var fn = function(clz) { clz.apply(this,clz.arguments) } fn.prototype = clz.prototype; return new fn(clz); } function User(firstName,lastName){ var clz = arguments.callee; //allow simple Class Instantiation if(!(this instanceof clz )) return makeInstance(clz); this.setName( firstName + ' ' + lastName ); }

Without using the new operator, we need to pay extra price foro the instantiation process, though it looks simpler to developers.

The Test