Wednesday, February 16, 2011

What happens when a Javascript constructor returns?

function T(){return T.a}
T.a = new T();
T.b = new T();
T.a == T.b

If you run this, the last statement will be true. Why?

The basic concept in a constructor's return statement is that if the return value is a primitive (null, number, boolean) then the result will be as expected. The "new" statement will return a reference to the newly created object. If the return is a reference, then that is what will be returned.

Thus when T.a = new T(); is called, T.a is undefined and the reference to the newly created object is returned. When T.b = new T(); is called T.a is defined and the reference to T.a is assigned to T.b. That is why the final statement T.a == T.b is true.

This is an interesting way to implement singletons in Javascript without having to write any special methods or use any other techniques.

You can also implement the Flyweight design pattern after majority of the program is written using a constructor.


  1. Is this behavior consistent among browsers?

  2. It works on all the browsers I have tested: Chrome, Firefox and Safari, but someone on Reddit mentioned that this will not work if Javascript "strict mode" is used. I haven't tested this myself as you need Firefox 4 Beta as of now.