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:
- Put the 
MyNamespacein a global scope; - Avoid redefining 
MyNamespacein 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.js
var MyNamespace = MyNamespace || {};
$(document).ready(function() {
   console.log(MyNamespace);
});
// second.js
var MyNamespace = MyNamespace || {};
$(document).ready(function() {
   console.log(MyNamespace);
});
Solution 2:
It should work if you define your variable outside of the document ready handler -
var MyNamespace = {};
$(document).ready(function() {
    console.log(MyNamespace);
});
Solution 3:
Create the namespace outside the scope, then add methods to it within the scope:
var MyNamespace = {};
$(document).ready(function() {
   MyNamespace.MyFunction = function () { ... };
});
$(document).ready(function() {
   console.log(MyNamespace);
});
Solution 4:
Create it outside and update it inside:
var MyNamespace = {};
$(document).ready(function() {
   MyNamespace.Example = new function() { // 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() {..});"