添加JavaScript重载函数的辅助方法

大家都习惯了重载带来的便利。JavaScript有没有重载呢?
有人会回答没有,因为函数会被覆盖;有人说有,我们可以模拟重载这 一操作。
JavaScript的重载函数,一般是靠对arguments判断来操作的。
比如:
var afunc = function() {
   args = arguments;
   if(args.length == 1) {
       console.log(1);
   }else if(args.length == 2) {
       console.log(2);
   }else if (args.length == 3) {
       console.log(3);
   }
} 
可以想象如果重载数量多的时候,要有多少的if-else判断啊(事实上重载数量应该不会太多吧)。
如果要对js函数进行重载,代码量肯定是多的。那么能不能想办法使代码清晰点,再减少那些相同代码的书写呢?
这就是我写篇文章和相关代码的起因了。
惯例先上代码:

    /** KOverLoad
    一个创建重载函数的辅助方法。
    其实这个方法只是帮忙整理了参数不同的情况下的重载方法。
    如果还要对参数类型进行判断重载的话,请在提供的方法中自己实现。
    @Author ake  2010-05-02
    @weblog http://www.cnblogs.com/akecn
    */
    var KOverLoad = function(scope) {
        this.scope = scope || window;   //默认添加方法到这个对象中。同时添加的方法的this指向该对象。
        this.list = {}; //存放重载函数的地方。
        return this;
    };
    KOverLoad.prototype = {
        //添加一个重载的方法。
        //@param arg<Function> 重载的方法。
        add:function(arg) {
            if(typeof arg == "function") {
                this.list[arg.length] = arg;    //以参数数量做标识存储重载方法。很显然如果你的重载方法参数数量
            }
            return this;
        },
        //添加完所有的重载函数以后,调用该方法来创建重载函数。
        //@param fc<String> 重载函数的方法名。
        load:function(fc) {
            var self = this, args, len;
            this.scope[fc] = function() {   //将指定作用域的指定方法 设为重载函数。
                args = Array.prototype.slice.call(arguments, 0);    //将参数转换为数组。
                len = args.length;
                if(self.list[len]) {    //根据参数数量调用符合的重载方法。
                    self.list[len].apply(self.scope, args); //这里指定了作用域和参数。
                }else{
                    throw new Error("undefined overload type");
                }
            }
        }
    };

使用 方法是我觉得比较清晰的方法:
//这是可选的作用对象。
   var s =function(){}
   s.prototype = {
       init:function() {
           console.log();
       }
   }
//构造函数的参数可以是Object类型的或者其他合法的类型,如果不指定,则注册到window对象中,并且作用域也是window。其实就是添加该重载方法到什么地方而已。
   new KOverLoad(s.prototype).add(function(a) {
       console.log("one",a,this)
   })

 

 .add(function(a,b) {
       console.log("two",a,b,this)
   })

 .add(function(a,b,c) {
       console.log("three",a,b,c,this)
   })

 .add(function(a,b,c,d) {
       console.log("four",a,b,c,d,this)
   })

 .load("func"); //在这里的参数就是要创建的重载函数的方法名称。

完成以上操作以后,s.func就是一个重载函数。
我们可以这样调用重载函数:
var t = new s();
t.func();//抛出错误异常。因为没有指定零参数时的函数
t.func(”o”);//one o Object {}
t.func(1,2);//two 1 2 Object {}

简单的代码而已,如果各位有建议或者意见,欢迎留言指教。

posted on 2010-05-02 21:30  Akecn  阅读(835)  评论(5编辑  收藏  举报