views:

76

answers:

1

Hey, I've got a question about self invoking functions in javascript.

What I'm doing is something similar to the following

myNamespace =  {}; //namespace for holding any objects/functions 

//helpModule as an example

myNamespace.HelpModule = new (function(){
    this.abc = '123';
    //lots of other code in here...
})();

now I'm able to access properties of myNamespace.HelpModule like so:

alert(myNamespace.HelpModule.abc);

But for starters jsLint doesn't like that saying "Weird construction. Delete 'new'.", And this page states that you shouldn't use Function Constructor, although in this case I'm not sure if its using the Function Constructor since its a self invoking function?

Anyway, it seems to work fine, and the reason I'm using it is to have "this" scope to the function instead of the global object (window). I could just defining it as an object literal or do something similar to

myNamespace.HelpModule = (function(){
    var obj = {};
    obj.abc = '123';

    return obj;
}();

but neither of these seem as "elegant" to me.

I'm wondering if this is bad form/practice?

+2  A: 

It is weird because the purpose of defining a constructor is to be able to reuse it to create many objects.

For your purpose, you can use this construct-

myNamespace.HelpModule = (function(){
    //private stuff here
    var a = 100;
    return {
        //public stuff here
        b : 200,
        something: function() {
            return a + this.b;
        }
    };
})();
Chetan Sastry
Hmm yeah that's sort of similar to my second code example, but more elegant. But the problem I have with object literals is, say for example using jQuery I want to bind some events to the object using $.bind I would have to wait until after the object is defined, and in your case would have to do $(myNamespace.HelpModule).bind('myEvent', function(){ etc.. }); after the self invoking function. So its not a nicely self contained piece of code
RueTheWhirled