0

Can I put similar methods in an associative aray like this?

var function_hold = {   
  function1: function(){}
  function2: function (){}
 };

If not,

How do I group similar methods?

  • 1
    Yes, though strictly speaking it's a stretch to call JavaScript objects "associative arrays". (The property namespace of an object can be "polluted" somewhat through prototypal inheritance effects.) – Pointy Nov 07 '11 at 22:38

4 Answers4

1

Yes thats possible and works fine.

Best Practice syntax would be the Module Pattern

var outerNamespace = {};

(function(ns) {
   // ns is the local name of the object
   ns.function1 = function() {}
   ns.function2 = function() {}

  //self executing anonymous function
} (outerNamespace));
FloydThreepwood
  • 1,587
  • 14
  • 24
1

Similarly as you would with any other object-oriented programming language, you group functionality in objects. This works in JavaScript as well.

Your code actually creates an object. Alternatively you can use JavaScript's prototype mechanism.

var Person = function(firstname, surname){
    this.firstname = firstname;
    this.surname = surname;
}

Person.prototype.getFullName = function(){
    return this.firstname + " " + this.surname;
}

You then call it like

var tom = new Person("Tom", "Jackwood");
tom.getFullName();
Juri
  • 32,424
  • 20
  • 102
  • 136
0

Yeah, that should would just fine.

moteutsch
  • 3,741
  • 3
  • 29
  • 35
0

Yes, that will work fine. You can call the functions with function_hold.function1().

Note that normally you'll want to associate data with the functions as well:

var function_hold = {
    x: 0,
    function1: function(){
        this.x++;
    }
    function2: function(){
        alert(this.x);
    }
};
Eric
  • 95,302
  • 53
  • 242
  • 374