/* * config * caoke */ ‘use strict‘; Object.extend=function(props){ //继承父类 var prototype=Object.create(this.prototype) //初始化函数ctor var _Class=function(){ if(arguments.length>0){ var sp=new _Class() if (sp.constructor){ sp.constructor.apply(sp, arguments); } return sp; } } //当前类属性和方法 for(var k in props){ prototype[k]= props[k] } _Class.prototype = prototype; //类继承 _Class.extend=this.extend; //类扩展 _Class.expand = function (prop) { for (var name in prop) { prototype[name] = prop[name]; } }; return _Class } //You can‘t use merge in util.js function merge(source, target){ if(typeof source === ‘object‘ && typeof target === ‘object‘){ for(var key in target){ if(target.hasOwnProperty(key)){ source[key] = merge(source[key], target[key]); } } } else { source = target; } return source; } var Config = Object.extend({ constructor : function(){ this.init.apply(this, arguments); }, init : function(){ this.data = {}; if(arguments.length > 0){ this.merge.apply(this, arguments); } return this; }, get : function(path, def){ var result = this.data || {}; (path || ‘‘).split(‘.‘).forEach(function(key){ if(key && (typeof result !== ‘undefined‘)){ result = result[key]; } }); if(typeof result === ‘undefined‘){ return def; } else { return result; } }, set : function(path, value){ if(typeof value === ‘undefined‘){ this.data = path; } else { path = String(path || ‘‘).trim(); if(path){ var paths = path.split(‘.‘), last = paths.pop(), data = this.data || {}; paths.forEach(function(key){ var type = typeof data[key]; if(type === ‘object‘){ data = data[key]; } else if(type === ‘undefined‘){ data = data[key] = {}; } else { console.error(‘forbidden to set property[‘ + key + ‘] of [‘ + type + ‘] data‘); } }); data[last] = value; } } return this; }, del : function(path){ path = String(path || ‘‘).trim(); if(path){ var paths = path.split(‘.‘), data = this.data, last = paths.pop(), key; for(var i = 0, len = paths.length; i < len; i++){ key = paths[i]; if(typeof data[key] === ‘object‘){ data = data[key]; } else { return this; } } if(typeof data[last] !== ‘undefined‘){ delete data[last]; } } return this; }, merge : function(){ var self = this; [].slice.call(arguments).forEach(function(arg){ if(typeof arg === ‘object‘){ merge(self.data, arg); } else { console.warning(‘unable to merge data[‘ + arg + ‘].‘); } }); return this; } }); module.exports = Config;
原文:http://www.cnblogs.com/caoke/p/6269178.html