oop.js

3581 단어 oop
oop.js

/**
 *  .
 * 
 * @author bisoft
 * @version 1.0 2013-07-23
 */
(function(global) {
	
	//  
	var override = function(s, t) {
		var i;
		for(i in t) {
			s[i] = t[i];
		}
	};
	
	//  
	var extend = function(subclass, supclass, options) {
		if (subclass.prototype !== Object.prototype) {
			var Root0 = function() {};
			Root0.prototype = supclass.prototype;
			var sbp = subclass.prototype = new Root0();
			sbp.constructor = subclass;
			if (options) {
				override(sbp, options);
			}
		}
	};
	
	//  
	var define = function(subClassName, options) {
		var supClassName = options['extend'] || 'Object';
		var supclass = get(supClassName);
		
		var subclass = options['constructor'];
		//  ,  
		extend(subclass, supclass, options);
		override(subclass.prototype, {
			'$className' : subClassName,
			'$class' : subclass,
			'$supClassName' : supClassName,
			'$superClass' : supclass
		});
		
		register(subClassName, subclass);
		
		var pkg = subClassName.indexOf('.') != -1 ? subClassName.split('.').slice(0, -1) : [];
		var shortClassName = subClassName.indexOf('.') != -1 ? subClassName.split('.').slice(-1) : subClassName;
		var ns = namespace(pkg);
		ns[shortClassName] = subclass;
		return subclass;
	};

	//  
	var create = function(className, options) {
		var cls = get(className);
		var o = new cls();
		
		//  
		cls.prototype.$superClass.call(o, options);
		//  
		if (options) {
			override(o, options);
		}
		
		return o;
	};
	
	var cache = {
		'Object' : Object
	};
	
	var register = function(name, value) {
		cache[name] = value;
	};
	
	var get = function(name) {
		return cache[name];
	};
	
	var namespace = function(name) {
		var namespaces = name.indexOf('.') != -1 ? name.split('.') : name;
		var i = 0;
		var pNamespace = global;
		for(i in namespaces) {
			var ns = namespaces[i];
			if (pNamespace[ns] === undefined) {
				pNamespace[ns] = {};
			}
			pNamespace = pNamespace[ns];
		}
		return pNamespace;
	};
	
	global.oop = (function() {
		return {
			define : define,
			create : create
		};
	})();
	
	
})(window);
 

oop.define('wldm.app.Controller', {
	constructor: function() {
		
	}
});

oop.define('wldm.app.Application', {
	extend : 'wldm.app.Controller',
	constructor: function() {
		
	}
});

var controller = oop.create('wldm.app.Controller');
var application = oop.create('wldm.app.Application');

console.log(controller instanceof wldm.app.Controller); // true
console.log(controller instanceof wldm.app.Application); // false
console.log(controller instanceof Object); // true

console.log(application instanceof wldm.app.Controller); // true
console.log(application instanceof wldm.app.Application); // true
console.log(application instanceof Object); // true
 

좋은 웹페이지 즐겨찾기