// first.js
$(document).ready(function() {
var MyNamespace = {};
});
// second.js
$(document).ready(function() {
console.log(MyNamespace);
});
Running this script I’m getting error Uncaught ReferenceError: MyNamespace is not defined. I suppose, I’m getting this error because definition of MyNamespace and MyNamespace calling are in different scopes. How do I solve this problem?
I need to create namespace inside $(document).ready() wrapper because functions in this namespace will use jQuery methods etc.
What is the best practice?
Thank you!
There are two things you need to change:
MyNamespacein a global scope;MyNamespacein each file;You put
var MyNamespace = MyNamespace || {};in front of both your js files. It decalresMyNamespaceas an object if it isn’t defined before.