Reputation: 690
Let's say I have these files: a.js b.js c.js which each one is defined like this:
(function(){
function afunction() {
}
function yetanotherfunction() {
}
... ...
})();
I also have a file named common.js, which contains functions that can be shared by multiples:
function commonFunction() {
}
function yetAnotherCommonFunction() {
}
I would like to put commonFunction, yetAnotherCommonFunction inside scope. ie:
(function() {
... //commonFunction, yetAnotherCommonFunction goes here
})();
however if I do so, I won't be able to call the common functions from a/b/c.js scope. Is there a better way to handle this?
Upvotes: 0
Views: 188
Reputation: 292
You can create a namespace for each script. A simple script to do this would be to have a namespace script like this :
var ns = function (namespace, callback) {
var nssplit = namespace.split('.'), x, curObj = window, curPos = null, lasObj;
for (x = 0 ; x < nssplit.length ; x++) {
curPos = nssplit[x];
if (curObj[curPos] === undefined) {
curObj[curPos] = {};
}
lasObj = curObj;
curObj = curObj[curPos];
}
lasObj[curPos] = callback;
};
ns('local.test', function() {
document.getElementById('test').innerHTML = "test";
});
local.test();
You can see it in action here http://jsfiddle.net/Nemesis02/Qtq8Q/
Upvotes: 0
Reputation: 23250
Namespaces:
var Common = (function () {
var Common = {};
Common.commonFunction = function() {
}
return Common;
}())
Common.commonFunction() // do something from anywhere
Upvotes: 4