1

I'm just learning JavaScript coming from a Java background and I have a question that I can't seem to get Google to answer!

When creating an object, let's say a Person object. Is it not possible to create a separate file named Person (like in Java) and use this again and again for separate websites? Or do you have to write what properties and methods the Person object should contain in every single site you want to use it on?

Is there no way to do this like in Java, where you have object classes?

Thanks :)

exexzian
  • 7,782
  • 6
  • 41
  • 52
  • 1
    *" Is it not possible to create a seperate file named Person (like i Java) and use this again and again for seperate websites?"* It's entirely possible. When you put JS code in a file, you can include that file with ``. Look at these resources to learn JavaScript: https://developer.mozilla.org/en/learn/javascript, http://eloquentjavascript.net/. – Felix Kling Jun 09 '13 at 20:54
  • 1
    http://stackoverflow.com/questions/2608913/how-can-i-write-reusable-javascript – ShiftyThomas Jun 09 '13 at 20:54
  • 1
    *"Is it no way to do this like in Java, where you have object classes?*" JavaScript does not have the concept of classes in the traditional sense. But it has **constructor functions** with which you can achieve similar effects. Have a look at http://eloquentjavascript.net/chapter8.html. – Felix Kling Jun 09 '13 at 20:58
  • Thanks, both of you! :) Appreciate any help I can get! –  Jun 09 '13 at 21:09

2 Answers2

3

You can either use require.js that gives a more programmatic style to your software modularity, or call all your scripts with <script src=""></script> tags in your main html code... As javascript loads all toplevels object in the same global environment, they will be available throughout all your scripts.

Many other ways to load javascript are given in that answer.

Community
  • 1
  • 1
zmo
  • 24,463
  • 4
  • 54
  • 90
1

Just include the JavaScript you want which defines the object on the page and you should be good to go. Note that the order in which you include these files does matter.

Example:

<script src="js1.js" type="text/javascript"></script> // contains class
<script src="js2.js" type="text/javascript"></script>
Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43
  • But what if I want to use the same Person object in several external java script files? Do I have to write the same object defining code in every js file? EDIT: The example helped! Thanks! I'll try this! :) –  Jun 09 '13 at 20:55