lang.js庫提供了包和類的定義、類的繼承與混合(mixin)、函數重載等功能,基本可滿足大多數物件導向設計的需求。同時支援基於鏈式的定義方式,讓庫在使用時更加規範和便捷。下面首先通過簡單的例子示範了lang.js的準系統,之後給出了lang.js的源碼及注釋。
一.功能介紹
“lang”作為架構的全域定義,其中包括了四個方法:
lang.Package(string name) //用於定義包(預設會暴露到全域)
lang.Class(string name[, object config], object classBody) //用於定義類
lang.Object(string name | object body) //用於定義支援重載函數的普通對象
lang.Function(string name | object body) //用於定義重載函數
複製代碼 代碼如下:var lang = (function(){
/***********************************
Javascript物件導向擴充庫(lang.js v1.0)
By: X!ao_f
QQ: 120000512
Mail: xiao_f.mail#163.com
************************************/
var customToString = function(){
return '[' + this.Type.type + ' ' + this.Type.name + ']';
}
//支援重載的方法定義
var createMethod = (function(){
//建立一個代理函數
var createMethodProxy = function(context, name){
//當調用重載的函數時,首先會執行該函數分析傳入的參數,進行匹配和轉寄
var method = function(){
//在第一次調用時初始化,將映射資訊緩衝
if(!method.__initialized__){
initializeMethod(method);
}
//將參數類型拼接成函數簽名
var signature;
if(arguments.length){
var list = [];
for(var i=0; i<arguments.length; i++){
var typename;
var argument = arguments[i];
if(argument === undefined || argument === null){
typename = 'object';
}else if(argument instanceof Array){
typename = 'array';
}else if(argument instanceof Date){
typename = 'date';
}else{
typename = typeof argument;
if(typename == 'object'){
if('Class' in argument){
typename = argument.Class.Type.name;
}else if('nodeType' in argument){
typename = 'element';
}
}
}
list.push(typename);
}
signature = list.join(',');
}else{
signature = '';
}
//如果常規緩衝中存在匹配的簽名,直接調用
if(method.__overloads__[signature]){
return method.__overloads__[signature].apply(this, arguments);
}else{
//緩衝中不存在時,嘗試利用正則進行模糊比對
//首先判斷模糊比對緩衝中是否存在記錄,如存在直接調用
if(method.__overloadsCache__[signature]){
return method.__overloadsCache__[signature].apply(this, arguments);
}
//迴圈匹配
for(var i=0; i<method.__overloadsRegExp__.length; i++){
//如果匹配成功,將映射關係存入模糊比對緩衝,同時調用並返回
if(method.__overloadsRegExp__[i].regexp.test(signature)){
method.__overloadsCache__[signature] = method.__overloadsRegExp__[i].fn;
return method.__overloadsRegExp__[i].fn.apply(this, arguments);
}
}
//如果依然無法找到對應的函數,判斷是否存在預設函數
if(method.__overloads__['default']){
return method.__overloads__['default'].apply(this, arguments);
}else if(method.__overloads__['']){
return method.__overloads__[''].apply(this, arguments);
}else{
alert('Error: '+method.Type.name+'('+signature+') is undefined.');
}
}
};
//內建對象
method.__context__ = context;
method.__functions__ = {};
method.toString = customToString;
//自描述資訊
method.Type = {
name: name,
Method: method,
type: 'method'
};
return method;
}
//初始化
var initializeMethod = function(method){
//基礎簽名緩衝
method.__overloads__ = {};
//模糊比對正則緩衝
method.__overloadsRegExp__ = [];
//模糊比對結果緩衝
method.__overloadsCache__ = {};
//例舉所有定義的函數
for(var signature in method.__functions__){
var fn = method.__functions__[signature];
var params = signature.substring(signature.indexOf('(') + 1, signature.length - 1);
var pure = !/[\*\+\?\{]/.test(params);
//如果不存在萬用字元直接儲存到基礎簽名緩衝
if(pure){
method.__overloads__[params] = fn;
}else{
//產生模糊比對正則
var regexp = '^' + params
.replace(/([\w\.]+)(\{.*?\})?/g, '($1(,|$))$2')
.replace(/\./g, '\\.')
.replace(/((\()var(\())/g, '$2\\w+$3')
.replace(/,\(/g, '(') + '$';
method.__overloadsRegExp__.push({ regexp: new RegExp(regexp), fn: fn });
}
}
method.__initialized__ = true;
}
//返回外部的定義函數
return function(signature, fn, comp){
//如果傳入的為一個對象,視為定義匿名方法
if(typeof signature == 'object'){
var context = {};
var method;
for(var key in signature){
method = createMethod.call(context, 'anonymous'+key, signature[key]);
}
return method;
}
signature = signature.replace(/\s+/g, '');
var index = signature.indexOf('(');
var name = index > -1 ? signature.substring(0, signature.indexOf('(')) : signature;
var context = this;
var method = context[name];
//上下文中不存在函數定義,視為第一次定義
if(method === undefined){
context[name] = method = createMethodProxy(context, name);
}else if(!method.Type || method.Type.type!='method'){
//上下文存在的函數是原生函數,將這個函數作為預設函數存入列表
var temp = method;
context[name] = method = createMethodProxy(context, name);
method.__functions__[name + '()'] = temp;
}else{
//如果上下文不同,建立新的重載方法並將已經存在的函數複製,這裡主要解決類繼承中子類與父類衝突的問題
//如果上下文相同,直接將初始化標記設為false,待下次調用時重新初始化
if(method.__context__ !== context){
var temp = method;
context[name] = method = createMethodProxy(context);
for(var sign in temp.__functions__){
method.__functions__[sign] = temp.__functions__[sign];
}
}else{
method.__initialized__ = false;
}
}
//將本次定義的函數添加到函數列表
//先入為主策略
if(comp){
if(fn.__functions__){
for(var key in fn.__functions__){
if(key in method.__functions__){
method.__functions__[key].__overridden__ = fn;
}else{
method.__functions__[key] = fn;
}
}
}else{
if(signature in method.__functions__){
method.__functions__[signature].__overridden__ = fn;
}else{
method.__functions__[signature] = fn;
}
}
}else{
//後入為主策略
if(fn.__functions__){
for(var key in fn.__functions__){
if(key in method.__functions__){
fn.__functions__[key].__overridden__ = method;
}
method.__functions__[key] = fn.__functions__[key];
}
}else{
if(signature in method.__functions__){
fn.__overridden__ = method;
}
method.__functions__[signature] = fn;
}
}
if(this.Type && this.Type.type == 'package'){
return this;
}else{
return method;
}
};
})();
//類定義函數
var createClass = (function(){
var slice = Array.prototype.slice;
var emptyFn = function(){};
var createClass = function(name){
return function(){
this[name].apply(this, slice.call(arguments, 0));
};
}
//用於調用被重寫函數
var baseCaller = function(){
if(arguments.length){
var args = slice.call(arguments, 0);
return baseCaller.caller.__overridden__.apply(this, args);
}else{
return baseCaller.caller.__overridden__.call(this);
}
}
//用於調用自身重載建構函式
var selfCaller = function(){
if(arguments.length){
var args = slice.call(arguments, 0);
return selfCaller.caller.__self__.apply(this, args);
}else{
return selfCaller.caller.__self__.call(this);
}
}
var filter = {prototype:true, Type:true};
//快速淺拷貝
function clone(a){
var fn = function(){};
fn.prototype = a;
return new fn;
}
//對象複製,替換存在的(後入為主)
function replace(base, self){
for(var key in self){
if(!(key in filter)){
if(typeof self[key] == 'function'){
//如果子類函數包含多載簽章或父類函數已經重載
if(key.indexOf('(') > -1 || (base[key] && base[key].__functions__)){
createMethod.call(base, key, self[key]);
}else{
//常規函數定義
if(key in base){
//記錄重寫資訊
self[key].__overridden__ = base[key];
}
base[key] = self[key];
}
}else{
base[key] = self[key];
}
}
}
}
//對象複製,只取補集(先入為主)
function complement(self, base){
for(var key in base){
if(!(key in filter)){
if(typeof base[key] == 'function'){
if(key.indexOf('(') > -1 || (self[key] && self[key].__functions__)){
createMethod.call(self, key, base[key], true);
}else{
if(key in self){
//記錄重寫資訊
self[key].__overridden__ = base[key];
}else{
self[key] = base[key];
}
}
}else if(!(key in self)){
self[key] = base[key];
}
}
}
}
return function(){
//處理參數
if(this.Type && this.Type.type == 'package'){
if(arguments.length == 2){
var name = arguments[0];
var body = arguments[1];
}else{
var name = arguments[0];
var config = arguments[1];
var body = arguments[2];
}
}else{
if(arguments.length == 1){
var name = 'Anonymous';
var body = arguments[0];
}else{
var name = 'Anonymous';
var config = arguments[0];
var body = arguments[1];
}
}
//建立類的基礎函數
var clazz = createClass(name);
//擷取父類資訊
var baseClass;
if(config && config.extend){
baseClass = config.extend;
}
//如果傳入的主體為函數,取其傳回值
if(typeof body == 'function'){
body = body(clazz);
}
//處理靜態成員
if(body.Static){
complement(clazz, body.Static);
delete body.Static;
body = body.Public||body;
}else{
body = body.Public||body;
}
//處理繼承
if(baseClass){
//通過快速淺拷貝複製父類成員
clazz.prototype = clone(baseClass.prototype);
//繼承靜態成員
complement(clazz, baseClass);
//繼承類成員
complement(clazz.prototype, body);
}else{
//不存在繼承
clazz.prototype = {};
complement(clazz.prototype, body);
}
//處理混合
if(config && config.mixin){
var mixin = config.mixin;
if(mixin instanceof Array){
for(var i=0; i<mixin.length; i++){
replace(clazz.prototype, mixin[i]);
}
}else{
replace(clazz.prototype, mixin);
}
}
//添加內建函數
clazz.prototype.base = baseCaller;
clazz.prototype.self = selfCaller;
clazz.prototype.constructor = clazz;
clazz.prototype.toString = customToString;
clazz.toString = customToString;
clazz.prototype.Class = clazz;
if(clazz.prototype[name]){
var constructor = clazz.prototype[name];
if(constructor.__functions__){
for(var key in constructor.__functions__){
//存在重載時,添加自身引用,用於通過this.self調用重載建構函式
constructor.__functions__[key].__self__ = constructor;
//存在繼承時,將父類的建構函式作為被重寫的函數,配置給當前類的建構函式
//用於通過base調用父類建構函式
if(baseClass){
constructor.__functions__[key].__overridden__ = baseClass.prototype[baseClass.Type.shortName];
}
}
}else if(baseClass){
clazz.prototype[name].__overridden__ = baseClass.prototype[baseClass.Type.shortName];
}
}else{
clazz.prototype[name] = emptyFn;
}
//類型自描述資訊
//如果當前上下文是一個包,將類添加到包中
if(this.Type && this.Type.type == 'package'){
clazz.Type = {
type:'class',
name: this.Type.name+'.'+name,
shortName: name,
Package: this,
Class: clazz,
baseClass: baseClass
}
clazz.prototype.Type = {
type: 'object',
name: this.Type.name+'.'+name
}
//將類添加到包
this[name] = clazz;
//調用靜態建構函式
if(name in clazz){
clazz[name].call(clazz);
}
//返回this用於鏈式調用
return this;
}else{
//上下文不是包則直接返回
clazz.Type = {
type:'class',
name: name,
shortName: name,
Class: clazz,
baseClass: baseClass
}
clazz.prototype.Type = {
type: 'object',
name: name,
baseClass: baseClass
}
if(name in clazz){
clazz[name].call(clazz);
}
return clazz;
}
};
})();
//用於建立支援重載的普通對象
var createObject = function(objects, config){
var target;
if(this.Type && this.Type.type == 'package'){
target = this;
}else{
target = {};
}
if(typeof objects == 'string'){
target = this[objects] = {};
objects = config;
}else if(typeof objects == 'function'){
objects = objects();
}
for(var key in objects){
if(typeof objects[key] == 'function' && (key.indexOf('(') > -1 || typeof target[key] == 'function')){
createMethod.call(target, key, objects[key]);
}else{
target[key] = objects[key];
}
}
if(this.Type && this.Type.type == 'package'){
return this;
}else{
return target;
}
};
//用於建立包
var createPackage = (function(){
var root = this;
return function(package){
var name = [];
var path = package.split('.');
var parent = root;
for(var i=0; i<path.length; i++){
name.push(path[i]);
if(parent[path[i]]){
parent = parent[path[i]];
}else{
var pack = {
Class: createClass,
Object: createObject,
Function: createMethod,
Package: createPackage,
toString: customToString
};
pack.Type = {
type: 'package',
Package: pack,
name: name.join('.')
}
parent = parent[path[i]] = pack;
}
}
return parent;
}
})();
//預設將Package暴露
window.Package = createPackage;
return {
Package: createPackage,
Class: createClass,
Function: createMethod,
Object: createObject
};
})();
結束語:
到這裡,lang.js的應用和原理就介紹完畢了,該庫在主流瀏覽器中均已測試通過,
如果想使用lang.js,可以在這裡免費下載,如發現什麼問題,或有好的建議可以反饋給我。