---
title: "JS实现动态创建类"
author: "yunchow"
date: "2013-04-12T19:26:15Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2013-04-12T19:26:15Z"
id: 1846587
url: "https://yunchow.iteye.com/blog/1846587"
---

```java



	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");





```