ITeye博客

JS实现动态创建类

yunchow · 2013-04-12 19:26 · 随意写的 · Web前端 · Markdown




	function declare(clazz, props) {
		var objs = clazz.split("."), parent = window;
		for (var i = 0; i < objs.length - 1; i++) {
			var o = objs[i];
			if (typeof o != 'object') {
				parent[o] = {};
				parent = parent[o];
			}
		}
		var fn = objs[objs.length - 1];
		if (typeof fn != 'function') {
			var c = parent[fn] = function() {
				props.constructor1.apply(this, arguments);
			}
			var constructorProto = c.prototype;
			for (p in props) {
				constructorProto[p] = props[p];
			}
		}
	}
	
	declare("com.ibm.wc.Common", {
		copyRight: "IBM All Rights",
		i: 123,
		j: 345,
		k: 'test',
		echo: function(msg) {
			alert("your message is " + msg + ", i = " + this.i + ", j = " + this.j);
		},
		constructor1: function(i, j) {
			this.i = i;
			this.j = j;
		}
	});
	var c = new com.ibm.wc.Common("Nick", 200);
	console.log(c);
	c.echo("hello");





评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。