Lydiafly

Coder,Like JS

导航

[原创]一个js函数重载功能

var _ = {
type2string:{},
type:function(s){
return s == null ? 'empty' : (_.type2string[Array.prototype.toString.call(s)] || 'object');
},
defined:function(type,f){
var fn = function(){
var args = Array.prototype.slice.call(arguments);
var i = 0, p , ff = fn['_'];
while(p = args[i++]){ ff = ff[_.type(p)]; }
if(!ff || !ff.fn){
ff = fn['_'];
if(ff && ff.fn){
return ff.fn.apply(fn,args);
}
throw new Error('function undefined!')
}
return ff.fn.apply(fn,args);
};
_._defined(type,fn,f);
fn['defined'] = function(type,f1){ return _._defined(type,fn,f1); };
return fn;
},
_defined:function(type,fn,source){
var types = fn['_'];
if(!types){ types = fn['_'] = {} }
if(_.type(type)=='function'){
types['fn'] = type;
return fn;
}
type.replace(/[^,]+/g,function(t){
types[t] = types[t] || {};
types = types[t];
});
types['fn'] = source;
return fn;
}
};
('Object,Function,String,Number,Boolean,Date,RegExp').replace(/[^,]+/g,function(a){
_.type2string['[object ' + a + ']'] = a.toLowerCase();
});
var a = _.defined(function(a,b){
//alert(['string|number']);
alert([a,b])
}).defined('string,string',function(s1,s2){
alert(['string|string',s1,s2]);
}).defined('string,object',function(s,o){
alert(['string|object',s,o])
});
a('1');
a('1','2');
a('1',{});
a('1',true);

posted on 2012-02-20 18:13  lydiafly  阅读(336)  评论(0编辑  收藏  举报