views:

45

answers:

1

OK. I have this lib for my internal project

(function() {
    var window = this,
        undefined; //guaranteed undefined

    var h3 = window.h3 = function (user) { return window.h3 = new h3.prototype.init(user); };

    h3.prototype = {
        init: function(user) {
            this.timestamp = +new Date;
            this.user = user;
            return this;
        },
        VERSION: '0.0.1', // Current version.
        timestamp: undefined,
        user: undefined,
        a: function() {alert('a');}
    };

    h3.prototype.init.prototype = h3.prototype;
})();

Here is a usecase: I need a lib that will store session user data and provide some functions for application like loading (via AJAX) information, display reports etc. Application is fully AJAX-driven. With help of jQuery i'll check for user credentials and init this lib with h3({user:'user_a',foo:'bar'}) call. Thus i will have a global object called h3 and can user it latter (say h3.a()). If i need to re-init this object i can do it with h3.init({user:'user_b',foo:'bla-bla-bla'}) call.
Design inspired by well-known jQuery lib.
And main question is - how good/bad is this? Can you help me to validate this design?

+2  A: 

I'm not at all sure what the prototyping is for, or the curious trick with init being both a method and a constructor, or the extra constructor wrapper. Best not to use too much JS magic if you can help it.

If, as it seems, you only have one global instance, forget prototyping and simplify:

var h3= {
    VERSION: '0.0.2',
    init: function(user) {
        this.user= user;
        this.timestamp= +new Date; // note, this. missing in original code
    },
    a: function() {
        alert('a');
    }
};
h3.init({user: 'user_a', foo: 'bar'});
bobince
Agree. Too mush is not good. All I want to achive is to prevent h3 usage before init it. Your way I can call `h3.a()` before init() call. I do not want it. In my version before init() call h3 is simply a wrapped init function...Thanks for `this.timestamp` - code edited.
NilColor
Well normally `a()` would do something with `user` so you'd definitely get an error if you called it. However otherwise it would seem relatively simple to put a `if (!('user' in this))` check in `a`.
bobince