var Namespace=(function(windows){
var _toArray = function(obj) {
// checks if it's an array
if (typeof(obj) == 'object' && obj.sort) {
return obj;
}
return new Array(obj);
};
var _namespace = function(identifier) {
var klasses = arguments[1] || false;
var ns = windows;
if (identifier != '') {
var parts = identifier.split(Namespace.separator);
for (var i = 0, j = parts.length; i < j; i++) {
if (!ns[parts[i]]) {
ns[parts[i]] = {};
}
ns = ns[parts[i]];
}
}
if (klasses) {
for (var klass in klasses) {
ns[klass] = klasses[klass];
}
}
//_dispatchEvent('create', { 'identifier': identifier });
return ns;
};
_namespace.use = function(identifier,isglobal) {
var _varscope =isglobal?windows:{};
var identifiers = _toArray(identifier);
var callback = arguments[1] || false;
for (var i = 0, j = identifiers.length; i < j; i++) {
identifier = identifiers[i];
var parts = identifier.split(Namespace.separator);
var target = parts.pop();
var ns = _namespace(parts.join(Namespace.separator));
if (target == '*') {
// imports all objects from the identifier, can't use include() in that case
for (var objectName in ns) {
_varscope[objectName] = ns[objectName];
}
} else {
// imports only one object
if (ns[target]) {
// the object exists, import it
_varscope[target] = ns[target];
}
}
}
return _varscope;
};
return _namespace;
})(window)
$.ajaxSetup({
cache: true
});
Namespace.separator = '.';
使用方式是:
var _Constant = Namespace('all.constant');
require(['commonutil'], function(ajaxUtil) {
ajaxUtil.callrest('/bases/v1/sso/token', function(data) {
if (data.code == "000000") {
var _Constant = Namespace('all.constant');
_Constant.TOKEN = data.data.TOKEN;
}
}, {}, false);
});
1
MinonHeart 2016-06-30 10:58:50 +08:00
相当于这样
require(['commonutil'], function(ajaxUtil) { ajaxUtil.callrest('/bases/v1/sso/token', function(data) { if (data.code == "000000") { window.all = window.all || {}; window.all.constant = window.all.constant || {}; var _Constant = window.all.constant; _Constant.TOKEN = data.data.TOKEN; } }, {}, false); }); |
2
withrock OP @MinonHeart 请问这样做的目的是什么?是防止污染全局命名空间么?
|
3
MinonHeart 2016-07-04 18:35:47 +08:00
@withrock 方便创建深层次的对象
|