I was not able to get your code to work in Chrome or Firefox, I always get the Main.width error Main.width .
The fact is that you are referring to the main inner particle when you are not yet fully constructed.
There is no easy solution, the best I can think of is to postpone the initialization part of your main singleton after you define the Particle class. Alternatively, you can also reorder the code to respect dependencies.
You must remember that in javascript, your code is evaluated when you call it.
Here are my two suggestions:
Solution 1 : Deferring Basic Initialization Partially
// Main.js --> loaded first var Main = new (function () { this.draw = true; this.width = 800; this.height = 600; // delayed initialization method this.init = function () { var p = new Particle(); this.print = function () { console.log(p.width, ':', p.height); } } })(); //Particle.js --> loaded second function Particle() { this.width = Main.width; this.height = Main.height; this.print = function() { console.log(this.width, ':', this.height); } } // call the delayed init method Main.init() var p = new Particle(); p.print(); Main.print();
Solution 2 : split into 3 files for dependency accounting
//Particle.js --> loaded first function Particle() { this.width = Main.width; this.height = Main.height; this.print = function() { console.log(this.width, ':', this.height); } } // Main.js --> loaded in second position var Main = (function() { var p = new Particle(); this.draw = true; this.width = 800; this.height = 600; function print() { console.log(p.width, ':', p.height); } return { draw : this.draw, width : this.width, height : this.height, print : print } })(); // Init.js --> loaded third var p = new Particle(); p.print(); Main.print();
source share