PeterAL
PeterAL

Reputation: 67

Creating an object through an object constructor in JS that is located in a separate js file

My problem in short: I've created an object constructor in a js file (file name: generation.js) and I would like to create an object with that constructor in an other js file (file name: timeline.js). When I try to do this, I get the error message: Uncaught ReferenceError: generation (the object I want to create) is not defined.

In the HTML I have the js files in proper order: first the generation.js, then timeline.js. I also have the jQuery line in place. If I try to use the constructor in the same file where the object definition is (in generation.js), it works properly. Then I copy + past that code to the new file and it doesn't work anymore.

The code:

Generation.JS:

This is where I defined the object constructor

$(document).ready(function(){

function  generation() {
    this.var1 = '';
    ....  // some variables
    this.genFactory = function(agents) { // some function that creates even more
    objects and other functions
    };
};
});

Timeline.JS:

This is where I would like to create an instance of the generation object

$(document).ready(function(){

   $('#start').click(function(){
          console.log('ASD'); //just to check if the file works
          gen1 = new generation(); //the error message points here
          gen1.genFactory(3);
          gen1.shuffle(individuals); //this is just an other method of the
          generation object

   });
});

Just to make sure that Timeline.js works: The console logs 'ASD'.

Looking forward for any suggestions!

Upvotes: 1

Views: 106

Answers (1)

Georgi-it
Georgi-it

Reputation: 3686

You should expose your generation function to the public by assigning it to the window. A general approach in such cases is to have an app variable which contains all such object constructors and variables. In your Generation.js file you should use this code:

$(document).ready(function(){

    window.app = window.app || {};

    app.generation = function () {
        this.var1 = '';
        ....  // some variables
        this.genFactory = function(agents) { // some function that creates even more
        objects and other functions
        };
    };
});

And in your Timeline.js file you will call your constructor as follows:

$(document).ready(function(){

    window.app = window.app || {};

   $('#start').click(function(){
          console.log('ASD'); //just to check if the file works
          gen1 = new app.generation(); //the error message points here
          gen1.genFactory(3);
          gen1.shuffle(individuals); //this is just an other method of the
          generation object

   });
})

Upvotes: 2

Related Questions