一个javascript面向对象类库

该类库主要依赖John Resig大神的Simple JavaScript Inheritance ,并对其做了修改.修改后的代码如下:

var C = (function(){
	// ------Class Creation------
    var initializing = false,
	fnTest = /xyz/.test(function() {
	    xyz;
	}) ? /\b_super\b/: /.*/;
	
	// The base Class implementation (does nothing)
	this.Class = function() {};
	
	// Create a new Class that inherits from this class
	Class.extend = function(prop) {
	    var _super = this.prototype;
	
	    // Instantiate a base class (but only create the instance,
	    // don't run the init constructor)
	    initializing = true;
	    var prototype = new this();
	    initializing = false;
	
	    // Copy the properties over onto the new prototype
	    for (var name in prop) {
	        // Check if we're overwriting an existing function
	        prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn) {
	            return function() {
	                var tmp = this._super;
	
	                // Add a new ._super() method that is the same method
	                // but on the super-class
	                this._super = _super[name];
	
	                // The method only need to be bound temporarily, so we
	                // remove it when we're done executing
	                var ret = fn.apply(this, arguments);
	                this._super = tmp;
	
	                return ret;
	            };
	        })(name, prop[name]) : prop[name];
	    }
	
	    // The dummy class constructor
	    function Class() {
	        // All construction is actually done in the init method
	        if (!initializing && this.init) this.init.apply(this, arguments);
	    }
	
	    // Populate our constructed prototype object
	    Class.prototype = prototype;
	
	    // Enforce the constructor to be what we expect
	    Class.prototype.constructor = Class;
	
	    // And make this class extendable
	    Class.extend = arguments.callee;
	
		// ------自定义方法------
	    /* 接口检查,参数可以是一个或多个,使用方法:
		 * //声明接口
		 * var Interface1 = Class.createInterface(['getName']);
		 * // Person类实现接口
		 * var Person = Class.extend({...}).impl(Interface1);
		 */
	    Class.impl = function() {
	        if (arguments.length > 0) {
	            for (var i = 0,
	            len = arguments.length; i < len; i++) {
	                var interfac = arguments[i];
	                if (!interfac._isInterfaceType) {
	                    throw new Error("Class.impl()第" + (i + 1) + "个参数必须是接口类型");
	                }
	                for (var j = 0,
	                methodLen = interfac.methods.length; j < methodLen; j++) {
	                    var method = interfac.methods[j];
	                    if (!prototype[method] || typeof prototype[method] !== "function") {
	                        throw new Error("类没有实现接口中的[" + method + "]方法");
	                    }
	                }
	            }
	        }
	
	        return Class;
	    };// ------自定义方法 end------
	
	    return Class;
	};// ------Class Creation end------
	
	// 接口辅助类
	var Interface = function(_methods) {
		if(typeof _methods.join !== "function") {
			throw new Error("参数" + _methods + "错误.创建接口参数只能有一个,并且为数组类型");
		}
		
		this.methods = [];
		this._isInterfaceType = true;

		for (var i = 0, len = _methods.length; i < len; i++) {
			if (typeof _methods[i] !== "string") {
				throw new Error("定义接口中的方法必须为字符串类型");
			}
			this.methods.push(_methods[i]);
		}
	};

	
	return {
		/**
		 * 创建一个类
		 * @param option 类方法,json数据
		 * @param parentClass 父类
		 */
		createClass:function(option,parentClass) {
			if(!parentClass) {
				parentClass = Class;
			}
			return parentClass.extend(option);
		}
		/**
		 * 创建一个接口
		 * @param methods 接口中的方法
		 */
		,createInterface:function(methods) {
			return new Interface(methods);
		}
	};
	
})();

类库中加上了接口验证功能,下面是使用方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS类的创建,继承,接口实现</title>
<script type="text/javascript" src="../src/core/C.js"></script>
<script type="text/javascript">
//-------------------------
// JS类的创建,继承,接口实现
//-------------------------

// 例子1:-------------------------
// 创建一个类
var Person = C.createClass({
	// 构造函数
	init:function(option){
		this.name = option.name;
	}
	,sayName:function() {
		console.log(this.name);
	}
	,getName:function() {
		return this.name;
	}
});

// 声明类实例
var Jim = new Person({name:'Jim'});
Jim.sayName();

//例子2:-------------------------

// 创建一个接口,接口里面有sayName方法
var Act = C.createInterface(['sayName']);

// 创建一个类,继承Person类,并实现Act接口
var Man = C.createClass({
	init:function(option) {
		this._super(option);// 调用父类构造函数
		this.age = option.age;
	}
	,sayAge:function() {
		console.log(this.age);
	}
},Person).impl(Act);

var man = new Man({name:'Tom',age:22});
man.sayName();
man.sayAge();

//例子3:-------------------------
// 创建接口
var Smile = C.createInterface(['smile']);
// 创建类,继承Person类,实现Act,Smile两个接口
var Woman = C.createClass({
	init:function(option) {
		this._super(option);
	}
	// override
	,smile:function() {
		console.log('hehe');
	}
	// override,重写Person类的sayName方法
	,sayName:function() {
		console.log('My name is ' + this.getName());
	}
	// override
	,getName:function() {
		// 调用父类的getName()
		var name = this._super();
		return '{'+name+'}';
	}
},Person).impl(Act,Smile);

var woman = new Woman({name:'Lily'});
woman.smile();
woman.sayName();

console.log(Jim instanceof Person);
console.log(man instanceof Person);
console.log(woman instanceof Person);
console.log(woman instanceof Woman);
</script>
</head>
<body>
</body>
</html>
由此可以见实现了类的创建,接口实现,继承,重写方法等基本功能.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值