Skip to content Skip to sidebar Skip to footer

Create "namespace" In $(document).ready(function() {..});

// first.js $(document).ready(function() { var MyNamespace = {}; }); // second.js $(document).ready(function() { console.log(MyNamespace); }); Running this script I'm getti

Solution 1:

There are two things you need to change:

  1. Put the MyNamespace in a global scope;
  2. Avoid redefiningMyNamespace in each file;

You put var MyNamespace = MyNamespace || {}; in front of both your js files. It decalres MyNamespace as an object if it isn't defined before.

// first.jsvarMyNamespace = MyNamespace || {};
$(document).ready(function() {
   console.log(MyNamespace);
});

// second.jsvarMyNamespace = MyNamespace || {};
$(document).ready(function() {
   console.log(MyNamespace);
});

Solution 2:

It should work if you define your variable outside of the document ready handler -

varMyNamespace = {};
$(document).ready(function() {
    console.log(MyNamespace);
});

Solution 3:

Create the namespace outside the scope, then add methods to it within the scope:

varMyNamespace = {};

$(document).ready(function() {
   MyNamespace.MyFunction = function () { ... };
});
$(document).ready(function() {
   console.log(MyNamespace);
});

Solution 4:

Create it outside and update it inside:

varMyNamespace = {};

$(document).ready(function() {
   MyNamespace.Example = newfunction() { // do something };
});

$(document).ready(function() {
   console.log(MyNamespace);
});

Solution 5:

Using var defines a variable local to the function, which is not visible outside of this scope. Leaving out var would define a global variable, accessible in the other function as well. In general you should rather avoid using global variables, but if that's what you need, simply say MyNamespace = {};

Post a Comment for "Create "namespace" In $(document).ready(function() {..});"