JavaScript NameSpace

摘要:JavaScript NameSpace

JavaScript的 NameSpace可以像這樣實做:

//something like this
var myNameSpase={};
myNameSpace.common={};
myNameSpace.common.tooltip=function(){};
//save as myNameSpace.common.js

如果其他地方要用只要把 myNameSpace.common.js檔加進來就可以了。

過一段時間,通常會變複雜…可能 myNameSpace.htmlTool.fnGG會用到 myNameSpace.common.fnYY…先不考慮架構清不清楚的問題,要怎麼在使用 myNameSpace.htmlTool.js的時候檢查有沒有先引用 myNameSpace.common.js?

function checkRequire(checkModels, errLogMsg, force){
	force = (typeof(force)==='boolean' ?force :false);
	errLogMsg = errLogMsg || '';
	
	var models = checkModels.split(',');
	for( var m=0, n=models.length; m<n; m++){
		var model = models[m];
		var nameSpace = model.split('.'), undefined;
		var root = window;
		for(var i=0, j=nameSpace.length; i<j; i++){
			var thisNameSpace = nameSpace[i];
			if(typeof root[thisNameSpace]==='undefined'){
				console.log(['need ', nameSpace.slice(0,i+1).join('.'), '; ', errLogMsg].join(''));
				if(force)
					return undefined;
			}
			else{
				root = root[thisNameSpace];
			}
		}
	}
	return true;
}
function checkRequireEval(checkModels, errLogMsg, force){
	force = (typeof(force)==='boolean' ?force :false);
	errLogMsg = errLogMsg || '';
	var models = checkModels.split(',');
	for( var m=0, n=models.length; m<n; m++){
		var model = models[m];
		var obj = eval(model);//if AA.BB === undefined, then AA.BB.CC will die without message; 然後發現不用 eval的函數有我沒考慮到的地方,但意外的符合我的需求XD
		if(typeof obj==='undefined'){
			console.log(['need ', model, '; ', errLogMsg].join(''));
			if(force){
				return undefined;
			}
		}
	}
	return true;
};
console.time('t1');
console.log('result1',checkRequire('AA.BB.CC.DD', 'must include', true) && 
		checkRequire('AA.FF, AA.GG', 'option include, a request need two or more models') 
		);
console.timeEnd('t1');//2ms
console.time('t2');
console.log('result1',checkRequireEval('AA.BB.CC.DD', 'must include', true) && 
		checkRequireEval('AA.FF, AA.GG', 'option include, a request need two or more models') 
		);
console.timeEnd('t2');//3ms

if(checkRequire('AA.BB.CC.DD', 'must include', true) && 
		checkRequire('AA.FF, AA.GG', 'option include, a request need two or more models')){
		// all include
}
else{
	return;//already log in function checkRequire
}

意外的發現 chrome也有 console.time可以用~