1

I've got an object defined as a function, and it's got a lot of methods and properties in it, what are some ways to modularise this to make it more manageable? It is possible to put functions inside the object into external files?

Edit:

Someone mentioned in one answer to include other files, but this would have an unweildy HTML page, IE:

<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
<script type="text/javascript" src="script3.js"></script>
....
<script type="text/javascript" src="script76.js"></script>

Is there also any way to structure the code so only one reference is required the the javascript file?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • You should generally try to have as few external scripts as possible. – Šime Vidas Nov 25 '10 at 13:52
  • What exactly "managing problems" do you have with your current code? – Šime Vidas Nov 25 '10 at 13:53
  • I have a object with a lot of methods in it, I would much prefer to have the functions split into seperate files into groups so they are a lot easier to manage than one huge file. – Tom Gullen Nov 25 '10 at 13:55
  • Is all the code needed on each web-page, or are you trying to split the code up into multiple files so that you can serve only the required functions to each web-page? btw, if you don't prefix your comment with "@Šime", I won't get a notification about your response. I believe "@Sime" works too in my case. – Šime Vidas Nov 25 '10 at 15:03

4 Answers4

3
var myobj = {
  somefunc: function() { /* function code */ },
  prop: "some string",
  // etc.
};

and in another js file included after the above code

myobj.anotherfunc = function () { /* function code */ };
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
Spliffster
  • 46
  • 1
1

You may want to check out RequireJS. It lets you define functions, modules, dependencies and load external Javascript files from Javascript (possibly async).

gblazex
  • 49,155
  • 12
  • 98
  • 91
0

you could use a server side script to handle your javascripts, with jsmin you could even speed up the process (if cached).

i'm thinking of a script somthing like this: scripts.php

<?php 

$files = array('script1.js', 'script2.js');
$output = '';

foreach($files as $file){
    $output .= file_get_contents($file);
}

header("Content-type: application/x-javascript");
echo $output;

?>

your html
<script type="text/javascript" src="/script.php"></script>

you could also just include all js files inside a folder, just generate the array via folder scanning or something, i think you get the idea!

greetings Nexum

Nexum
  • 63
  • 4
0

You could try this:
http://www.cryer.co.uk/resources/javascript/script17_include_js_from_js.htm

...but best practices are to just include the files you want in the main html page

Gerrat
  • 28,863
  • 9
  • 73
  • 101