TedTedTed
TedTedTed

Reputation: 33

How should I organise an object to to keep everything as decoupled as possible?

I am finally asking this question as I have never actually found an answer. If I have a javascript object with a structure such as this:

var someObj = {

    "categoryA" : {
        "func1" : function(){},
        "func2" : function(){},
    },

    "categoryB" : {
        "func3" : function(){},
        "func4" : function(){},
    }

}

func4 wants to call func2. Do I have any way of calling it without saying someObj.func2()? It seems to me this is ugly since it is ensuring the application cannot be easily renamed and appears to be more tightly coupling the internal functions. Or is this just how it is typically organised and it is not seen as a problem?

Upvotes: 3

Views: 63

Answers (3)

premek.v
premek.v

Reputation: 258

You can use some "private" variable name for using inside your module ('me' in my example) and "export" it to another variable for outside use ('someObj').

var someObj = (function(){
  var me = {
    A:{
      fn1:function() {return 1}
    },
    B:{
      fn2:function() {return me.A.fn1()}
    }
  };
  return me;
})();

someObj.B.fn2()

Upvotes: 1

qwertymk
qwertymk

Reputation: 35256

It's not really possible for the following reason. Imagine something like this:

var obj1 = {}, obj2 = {};

var categoryA = {
    "func1" : function(){},
    "func2" : function(){},
};

var categoryB = {
    "func3" : function(){},
    "func4" : function(){},
};

obj1.categoryA = categoryA;
obj1.categoryB = categoryB;

obj2.categoryA = categoryA;
obj2.categoryB = categoryB;

You can see that obj2.categoryB.func4() wouldn't know what to do.

Upvotes: 1

HoLyVieR
HoLyVieR

Reputation: 11134

You can always refractor your object declaration into something that looks like this :

var someObj = (function() {

    function func1(){}
    function func2() {}
    function func3() {}

    function func4() {
        func2();
    }

    var self = {
        "categoryA" : {
            "func1" : func1,
            "func2" : func2,
        },

        "categoryB" : {
            "func3" : func3,
            "func4" : func4,
        }
    };

    return self;
}());

It's commonly called the "Module Pattern".

Upvotes: 1

Related Questions