How to use the constructor for the JavaScript client

advertisements

I'm experimenting with a simple Javascript API client but not sure on how to implement the constructor pattern.

So far I have this (based on Stripe's NodeJS client):

//myapp.js
'use strict';

MyApp.DEFAULT_HOST = 'api.myapp.io';
MyApp.DEFAULT_PORT = '443';
MyApp.DEFAULT_BASE_PATH = '/v1/';

function MyApp() {
    if(!(this instanceof MyApp)) {
        return new MyApp();
    }

}

MyApp.prototype = {
    init: function(appId) {
        console.log("Initializing");
    }
}

and in the HTML file I have:

...
<head>
    <script type="text/javascript" src="myapp.js"</script>
    <script type="text/javascript">
        var client = new MyApp();
        client.init('12345');
    </script>
</head>
...

I don't want users of this client to need to add the var client = new MyApp(); line. How can I modify myapp.js so that users only need to use the MyApp.init('12345'); line like this:

...
<head>
    <script type="text/javascript" src="myapp.js"</script>
    <script type="text/javascript">
        MyApp.init('12345');
    </script>
</head>
...


This sounds like you want MyApp to be a singleton - which is neither a good practise nor has anything to do with constructors.

Don't use an init method but just put everything in the constructor:

function MyApp(appId) {
    if(!(this instanceof MyApp)) {
        return new MyApp(appId);
    }
    console.log("Initializing instance "+appId);
}
MyApp.DEFAULT_HOST = 'api.myapp.io';
MyApp.DEFAULT_PORT = '443';
MyApp.DEFAULT_BASE_PATH = '/v1/';

MyApp.prototype = … // add other methods

Your user would then just call var client = new MyApp('12345'). But notice that any side effects (like registering the instance in the DOM or something) should go in a separate method called on client.

If you want to simplify the instance creation, you can also use static methods, for example something like

function MyApp(appId) {
    console.log("Initializing instance "+appId);
}
MyApp.create = function(appId) {
    return new MyApp(appId);
};
MyApp.init = function(appId, …) {
    var client = this.create(appId);
    client.register(…);
    client.start(…);
    … // whatever
    return client;
};