首页 > 代码库 > JavaScript函数命名空间、参数类型重载实现

JavaScript函数命名空间、参数类型重载实现

有时候使用doFunc({arg1: xxx, arg2:xxx});不方便,还是得在参数表重载,而重载情况又多种多样弄得晕头转向,结果就试着写了这么个东西,也不知道有没有地方能用上:

 

<!DOCTYPE html><html lang="zh"><head>    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />    <title>命名空间、参数类型重载</title>    <script type="text/javascript" src="http://www.mamicode.com/arg-func.js"></script>    <script type="text/javascript">        (function () {            var MyFuncs = {                ‘myNamespace.exampleFunc(string str, number num)‘: function (str, num) {                    alert(‘str: ‘ + str + ‘ num: ‘ + num);                },                ‘myNamespace.exampleFunc(number num)‘: function (num) {                    alert(‘num: ‘ + num);                },                ‘myNamespace.exampleFunc(array)‘: function (arr) {                    alert(‘arr: ‘ + arr);                },                ‘myNamespace.exampleFunc()‘: function () {                    alert(‘无参数重载‘);                }            };            ArgFunc.parse(MyFuncs);        })();    </script></head><body>    <label>有效调用:</label><br />    <input type="button" value="http://www.mamicode.com/myNamespace.exampleFunc(‘abc‘,123)" onclick="myNamespace.exampleFunc(‘abc‘, 123)" /><br />    <input type="button" value="http://www.mamicode.com/myNamespace.exampleFunc(123)" onclick="myNamespace.exampleFunc(123)" /><br />    <input type="button" value="http://www.mamicode.com/myNamespace.exampleFunc([1,2,3])" onclick="myNamespace.exampleFunc([1, 2, 3])" /><br />    <input type="button" value="http://www.mamicode.com/myNamespace.exampleFunc()" onclick="myNamespace.exampleFunc()" /><br />    <label>无效调用:</label><br />    <input type="button" value="http://www.mamicode.com/myNamespace.exampleFunc(false)" onclick="myNamespace.exampleFunc(false)" /><br />    <input type="button" value="http://www.mamicode.com/myNamespace.exampleFunc(‘abc‘,123,[1,2,3])" onclick="myNamespace.exampleFunc(‘abc‘, 123, [1, 2, 3])" /><br /></body></html>

 

用到的arg-func.js:

(function () {    if (!String.prototype.trim) {        String.prototype.trim = function () {            return this.replace(/(^\s+)|(\s+$)/g, ‘‘);        };    }    var TYPE = { UNKOWN: null, UNDEFINED: ‘undefined‘, NULL: ‘null‘, BOOLEAN: ‘boolean‘, NUMBER: ‘number‘, STRING: ‘string‘, FUNCTION: ‘function‘, OBJECT: ‘object‘, ARRAY: ‘array‘ };    function getType(o) {        if (o === undefined) { return TYPE.UNDEFINED; }        if (o === null) { return TYPE.NULL; }        switch (typeof (o)) {            case TYPE.BOOLEAN: return TYPE.BOOLEAN;            case TYPE.NUMBER: return TYPE.NUMBER;            case TYPE.STRING: return TYPE.STRING;            case TYPE.FUNCTION: return TYPE.FUNCTION;        }        switch (Object.prototype.toString.call(o)) {            case ‘[object Array]‘: return TYPE.ARRAY;            case ‘[object Object]‘: return TYPE.OBJECT;            default: return o ? TYPE.OBJECT : TYPE.UNKOWN;        }    }    var _ArgFunc = {        _parse: function (format, func, namespace) {            var lp = format.indexOf(‘(‘), rp = format.indexOf(‘)‘);            var name = format.substring(0, lp);            var argTypes = format.substring(lp + 1, rp).split(‘,‘);            for (var i = 0, len = argTypes.length; i < len; i++) {                argTypes[i] = argTypes[i].trim().split(/ +/)[0];            }            argTypes = argTypes.join(‘,‘);            var nsnn = _ArgFunc._analyseNamespace(name, namespace);            namespace = nsnn.namespace;            name = nsnn.name;            var wrapperFunc = namespace[name];            if (!wrapperFunc) {                wrapperFunc = namespace[name] = function () {                    ArgFunc.apply(wrapperFunc, arguments);                };            }            if (wrapperFunc[argTypes]) {                throw ‘方法已存在参数类型一样的重载。‘;            } else {                wrapperFunc[argTypes] = func;            }        },        _analyseNamespace: function (name, upperNamespace) {            var namespace = upperNamespace || window;            var parts = name.split(‘.‘);            var name = parts.pop();            for (var i = 0, part; part = parts[i]; i++) {                if (!namespace[part]) {                    namespace[part] = {};                }                namespace = namespace[part];            }            return { namespace: namespace, name: name };        }    };    var ArgFunc = {        bind: function (funcs, prototype) {            ArgFunc.parse(funcs, prototype);        },        parse: function (funcs, namespace) {            if (arguments.length == 3) {                _ArgFunc._parse(arguments[0], arguments[1], arguments[2]);            } else if (getType(funcs) == TYPE.OBJECT) {                for (var format in funcs) {                    _ArgFunc._parse(format, funcs[format], namespace);                }            } else if (getType(funcs) = TYPE.ARRAY) {                for (var i = 0, func; func = funcs[i]; i++) {                    _ArgFunc._parse(func[0], func[1], namespace);                }            }        },        apply: function (func, args) {            var argTypes = [];            for (var i = 0, len = args.length; i < len; i++) {                var arg = args[i];                argTypes.push(getType(arg));            }            argTypes = argTypes.join(‘,‘);            func = func[argTypes];            if (!func) {                throw ‘没有找到参数类型匹配的重载方法‘;            } else {                func.apply(this, args);            }        }    };    if (!window[‘ArgFunc‘]) {        window[‘ArgFunc‘] = ArgFunc;    }})();

JavaScript函数命名空间、参数类型重载实现