0

I seem to run into a problem with name spacing in JavaScript.

I have separated my javascript objects into separate files.

Each file starts with namespace definition:

var MySystem = MySystem || {};

If I include the object, which calls some methods of the object that is included in the file after it - I get the TypeError saying that a given object does not exist.

Example of the problem I'm having:

File 1 Url.js (included first in the html document):

var MySystem = MySystem || {};

MySystem.Url = {

    objHelper : MySystem.Helper,

    init : function() {

        "use strict"

        if (this.objHelper.isEmpty('string')) {

            throw new Error('The string is empty');

        }

    }

}

File 2 Helper.js (included second in the html document):

var MySystem = MySystem || {};

MySystem.Helper = {

    isEmpty : function(thisValue) {

        "use strict"

        return (
            typeof thisValue === 'undefined' ||
            thisValue === false ||
            thisValue === null ||
            thisValue === ''
        );

    }

}

When called using MySystem.Url.init(); I get:

TypeError: this.objHelper is undefined  
if (this.objHelper.isEmpty('string')) {

When I reverse the order of the included files - everything works fine.

This is obviously very simple example, but my system consists of many more objects - all of them in their own, separate file.

What's the best workaround for this problem?

Spencer Mark
  • 5,263
  • 9
  • 29
  • 58
  • `if (this.objHelper && this.objHelper.isEmpty('string'))`? – Andy Aug 14 '14 at 11:32
  • 1
    `objHelper : MySystem.Helper` can only work if `MySystem.Helper` is defined first, which is the case only when you reverse the order of the files. – Sebastien C. Aug 14 '14 at 11:34
  • And there's no really way around it? I believe that without namespaces - by simply using straight objects it would work just fine, but I like the code organised :( – Spencer Mark Aug 14 '14 at 11:42
  • Why would you want to use `MySystem.Url.objHelper` instead of simply `MySystem.Helper`? – Bergi Aug 14 '14 at 12:11
  • Because it's a separate object - Url / Helper / Form / etc. Helper might be used in other objects as well. – Spencer Mark Aug 14 '14 at 13:28

1 Answers1

0

You try to reinvent module system. Use require.js http://requirejs.org/

Anton Tupy
  • 951
  • 5
  • 16
  • The OPs approach predates the existence of require.js… – Bergi Jan 19 '18 at 06:23
  • Yes, it is true. But this approach suffers from problems that are solved in the require.js and more common in AMD, CommonJS and and finally in ES6 modules. – Anton Tupy Jan 19 '18 at 08:18