添加JavaScript重载函数的辅助方法2——添加类型判断

话说,人就是要被关注才有动力啊。。

于是修改了下上次写的《添加JavaScript重载函数的辅助方法

在添加方法的时候增加了一个参数 用于限制参数的类型。

代码依然简单。所以依然没什么好解释的。。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/** KOverLoad
    一个创建重载函数的辅助方法。
    补充上次的函数。
    @Author ake  2010-07-03
    @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, types) {
            if(typeof arg == "function") {
                var types = (types || []).join(",");
                this.list[arg.length + types] = arg;    //以参数数量和类型做标识存储重载方法。很显然如果你的重载方法参数数量
                return this;
            }
        },
        checkTypes: function(types) {
            var type = [];
            //console.log(typeof type); []方式创建的数组,其typeof类型为object
            //如果需要判断类型的话  还是用Object.prototype.toString.call(type) == "[object Array]"来判断吧。
            for(var i=0, it; it = types[i++];) {
                type.push(typeof it);
            }
            return type.join(",");
        },
        //添加完所有的重载函数以后,调用该方法来创建重载函数。
        //@param fc<String> 重载函数的方法名。
        load:function(fc) {
            var self = this, args, len, types;
            this.scope[fc] = function() {   //将指定作用域的指定方法 设为重载函数。
                args = Array.prototype.slice.call(arguments);    //将参数转换为数组。
                len = args.length;
                types = self.checkTypes(args);
                //console.log(self.list);
                if(self.list[len + types]) {    //根据参数数量调用符合的重载方法。
                    self.list[len + types].apply(self.scope, args); //这里指定了作用域和参数。
                }else if(self.list[len]){
                    self.list[len].apply(self.scope, args)
                }else {
                    throw new Error("undefined overload type");
                }
            }
        }
    };

 

 

下面是示例:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var s = {};
new KOverLoad(s)  //设置方法绑定的位置。命名空间?
.add(function(a) {
    console.log("one",a,this)
},["string"])
.add(function(a,b) {
    console.log("two",a,b,this)
},["string","string"])
.add(function(a,b,c) {
    console.log("three",a,b,c,this)
},["string", "number", "string"])
.add(function(a,b,c,d) {
    console.log("four",a,b,c,d,this)
})
.load("func"); //在这里的参数就是要创建的重载函数的方法名称。
 
s.func("a","b");

 

 

posted on 2010-07-03 18:39  Akecn  阅读(354)  评论(0)    收藏  举报

< 2010年7月 >
27 28 29 30 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7

统计

点击右上角即可分享
微信分享提示