javascriptobjectexternal-js

How to access objects in an external js file from another external js file


Hello fellow programmers,

I am wondering today how to access objects from another external js file. I'm using this as a way to organize my code throughout multiple js files. Here's an example of what I'm trying to say.

Imagine this as the code from an external js file:

$(function () {

  function Person() {
    this.name = "Bob";
  }

})

And I want to access that object in another js file:

$(function () {

  var person = new Person;
  alert(person.name);

})

Is there a way to do something like that? How would I need to position the html?


Solution

  • My first wonder is why you have your JS wrapped in a function like so. You can see here I've accessed "hello" from another script loaded after it's set - as it's set in the global space.

    https://jsfiddle.net/sj7bp97c/

    <script src="https://pastebin.mozilla.org/?dl=8907696">
    </script>
    <script src="https://pastebin.mozilla.org/?dl=8907697">
    </script>
    

    One script sets the value, the other prints it to console. Unless it's required for your Javascript to be surrounded by functions, I'm not sure why you're doing so.