开发者

javascript new self invoking function

开发者 https://www.devze.com 2023-01-05 02:24 出处:网络
I\'ve got a question about self invoking functions in javascript. What I\'m doing is something similar to the following

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.HelpModu开发者_如何学编程le 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?


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;
        }
    };
})();
0

精彩评论

暂无评论...
验证码 换一张
取 消