most recent 30 from stackoverflow.com 2026-03-01T06:34:33Z https://stackoverflow.com/feeds/question/8043611 https://creativecommons.org/licenses/by-sa/4.0/rdf https://stackoverflow.com/q/8043611 0 user656925 https://stackoverflow.com/users/0 2011-11-07T22:35:48Z 2011-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#8043637 0 moteutsch https://stackoverflow.com/users/367322 2011-11-07T22:37:39Z 2011-11-07T22:37:39Z <p>Yeah, that should would just fine.</p> https://stackoverflow.com/questions/8043611/-/8043658#8043658 0 Eric https://stackoverflow.com/users/102441 2011-11-07T22:39:00Z 2011-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#8043663 1 FloydThreepwood https://stackoverflow.com/users/406181 2011-11-07T22:39:32Z 2011-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#8043678 1 Juri https://stackoverflow.com/users/50109 2011-11-07T22:40:23Z 2011-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>