mercredi 29 avril 2015

JavaScript scopes confusion with namespaces

I playing around with namespaces convention and attached code which confusing me a little bit.

MYOBJECT = {
     prop1: (function(){
         console.log(this.prop2); 
         // returning undefined as the window property
     })(),
     prop2: function(){
         console.log(this.prop2); 
         // returning prop2 function as the MYOBJECT  property
     },    
 }
 MYOBJECT.prop2();

JSFIDDLE

If I understand this situation, that mean when function is invoked, MYOBJECT is not initialized yet so this in that case is window (but I am not sure why it is window). That mean I cannot access prop2 from prop1 when prop1 is auto invoking function.

Of course I can create MYOBJECT.init where I will invoke all necessary functions, but I feel that this solution making mess in the code and forcing me to unnecessary repetations:

MYOBJECT = {
     init: function(){
         this.prop1();
         this.prop2();
     },
     prop1: (function(){
         console.log(this.prop2);
     }),
     prop2: function(){
         console.log(this.prop2);
     },
 }
 MYOBJECT.init();

It will be really nice to make it work like that:

MYOBJECT = {
    prop1: (function(){
         console.log(this.prop2);
    })(),
    prop2: (function(){
         console.log(this.prop2);
    })(),
}

But as established, it will not work.

Because in my system I am creating a lot of similar objects I want to automate initialization process, I had and idea to use a class which will do it for me:

AutoInit = function(properties){
    this.init(properties); 
}
AutoInit.prototype.init = function(properties){
    var key;
    for(key in properties){
        // it will init only properties starts with '_'
        if(properties.hasOwnProperty(key) && key.indexOf('_') === 0){
            properties[key]();
        }
    }
}


MYOBJECT = new AutoInit({
    _prop1: function(){
        console.log(this._prop2);
    },
    _prop2: function(){
        console.log(this._prop1);
        // public        
    },
});

JSFIDDLE

It works but It is not really fast solution, I am looking for something better but I cannot find.

My purpose is to have a namespaces structure where I will be able to use auto invoking functions which all of them will have access to another properties of the namespace. Any help will be appreciated.

Aucun commentaire:

Enregistrer un commentaire