most recent 30 from stackoverflow.com2026-03-01T06:34:33Zhttps://stackoverflow.com/feeds/question/8043611https://creativecommons.org/licenses/by-sa/4.0/rdfhttps://stackoverflow.com/q/80436110user656925https://stackoverflow.com/users/02011-11-07T22:35:48Z2011-12-24T19:51:17Z
<p>Can I put similar methods in an associative aray like this?</p>
<pre><code>var function_hold = {
function1: function(){}
function2: function (){}
};
</code></pre>
<p>If not,</p>
<p>How do I group similar methods?</p>
https://stackoverflow.com/questions/8043611/-/8043637#80436370moteutschhttps://stackoverflow.com/users/3673222011-11-07T22:37:39Z2011-11-07T22:37:39Z<p>Yeah, that should would just fine.</p>
https://stackoverflow.com/questions/8043611/-/8043658#80436580Erichttps://stackoverflow.com/users/1024412011-11-07T22:39:00Z2011-11-07T22:39:00Z<p>Yes, that will work fine. You can call the functions with <code>function_hold.function1()</code>.</p>
<p>Note that normally you'll want to associate data with the functions as well:</p>
<pre><code>var function_hold = {
x: 0,
function1: function(){
this.x++;
}
function2: function(){
alert(this.x);
}
};
</code></pre>
https://stackoverflow.com/questions/8043611/-/8043663#80436631FloydThreepwoodhttps://stackoverflow.com/users/4061812011-11-07T22:39:32Z2011-11-07T22:39:32Z<p>Yes thats possible and works fine.</p>
<p>Best Practice syntax would be the <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth" rel="nofollow">Module Pattern</a></p>
<pre><code>var outerNamespace = {};
(function(ns) {
// ns is the local name of the object
ns.function1 = function() {}
ns.function2 = function() {}
//self executing anonymous function
} (outerNamespace));
</code></pre>
https://stackoverflow.com/questions/8043611/-/8043678#80436781Jurihttps://stackoverflow.com/users/501092011-11-07T22:40:23Z2011-11-07T22:40:23Z<p>Similarly as you would with any other object-oriented programming language, you group functionality in objects. This works in JavaScript as well.</p>
<p>Your code actually creates an object. Alternatively you can use JavaScript's prototype mechanism.</p>
<pre><code>var Person = function(firstname, surname){
this.firstname = firstname;
this.surname = surname;
}
Person.prototype.getFullName = function(){
return this.firstname + " " + this.surname;
}
</code></pre>
<p>You then call it like</p>
<pre><code>var tom = new Person("Tom", "Jackwood");
tom.getFullName();
</code></pre>