Search code examples
javascriptoopcode-organization

Best way to organize methods and properties in a JavaScript object literal


What is the best way to organize your JavaScript object literals?

I usually do something like this:

var myObj = {
    property1 : 'string',
    property2 : true,
    method1 : function() {},
    method2 : function() {
        // Do something with method1 here
        method1();
    }
    init : function() {
        method2();
    }    
};

Basically, I have my global properties at the top, methods bellow.

Also, if I have a method caling another method, I write the lower level one first, and then the one dealing with it. This seamed logical to me, as you first read the more basic functionality and than the operations that are done with it. However I noticed people with more experience than me do it the other way around.

Is there a correct approach to do this or is it a matter of choice?

Also, I noticed in tutorials that usually people prefix some of the methods, like a build method or the init method, with an underscore, like _bulid or _init. Whats the logic behind this?


Solution

  • It actually depends on your program and the way you write code, because there are a lot of ways to namespace stuff in JS, and object literals are just one of them.

    regarding the _ prefix, JS has no built-in method of making "private members" in "classes". You'd have to use closures to emulate such. Otherwise, it means an object in JS always has its properties and methods public. As a convention to some, prefixing it with _ means that member is used as a private member.