1

I have some javascript code and to my mind code is messy. So i want to do something that allow me to avoid word 'object' when I invoke methods and work with fields. Can I do something with it?

object = {
    init: function() {
        object.someField = 1;
        object.anotherField = 2;
    }
};

object.someMethod = function(){
    object.anotherMethod();
};

object.anotherMethod = function(){
    alert('anotherMethod');    
};
alex.seluta
  • 89
  • 2
  • 7
  • Just change it to another word... – Paddy Dec 05 '14 at 15:08
  • I think about to avoid any word. Is it real? This is only an example but in my project I has a lot of methods and fields. – alex.seluta Dec 05 '14 at 15:11
  • If youre creating more then one instance you may consider using a constrictor function. If you want to avoid using object or this then bergis answer using closure could work for you. More about constructor functions and prototype can be found here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Dec 06 '14 at 00:00

3 Answers3

1

Take a look at the revealing module pattern:

var object = (function () {
    var someField,
        anotherField,

        init = function () {
            someField = 1;
            anotherField = 2;
        },
        someMethod = function () {
            anotherMethod();
        },
        anotherMethod = function () {
            alert(someField);
        };

    return {
        init: init,
        someMethod: someMethod
    };
})();

object.init();
object.someMethod();

jsfiddle example

This route has the added benefit of supporting private fields.

Nick
  • 14,291
  • 3
  • 17
  • 19
0

try the this keyword. Just make sure you use it properly.

Lodewijk Bogaards
  • 19,777
  • 3
  • 28
  • 52
-1

What you have in your question is a 'good' way to structure your script, effectively taking your functions out of the direct global scope.

If you had a script with a method:

function A()
{
    //Important code.
}

And at some point you add another plugin/different script file further down that page the uses A() that also declares a method A():

function A() {
    //Do something else
}

Then code will use the second definition of A and not call your important code. Tracking this down can be tricky. By using the prototypal code in your question you are kind of 'namespacing' your code and drastically reducing the chances of an accidental collision on method names, as the only item you put in the global scope is the 'object' name.

Paddy
  • 33,309
  • 15
  • 79
  • 114