JavaScript instantiation trick

If you develop any JavaScript application - one time there will be a moment when you need to use a factory.

Formally a factory is a function or method that returns objects of a varying prototype or class.


Here is a simple example:

function makeContext(window) {
    if (window.AudioContext) {
        return new window.AudioContext();
    return new window.webkitAudioContext();

Little trick

Okay, lets do some magic? I think you know how JS works with || operator:

var value = oldValue || newValue;

If the oldValue is not truth(ex: does not exists) - use newValue. So we can use it instead of a factory, like inline condition.

var context = new (window.AudioContext || window.webkitAudioContext)();

It helps when we do not know if first class actually exists. Also you can write as many classes as you want. 😃


I do not recommend you to work with inline factory because it is not so obvious as a good function with documentation. But it is not bad to know about such trick.

Thanks for reading and good luck!