码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 函数重载 overloading

时间:2016-11-15 00:15:09      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:asc   example   code   ram   实现   pre   url   ring   var   

函数重载

https://en.wikipedia.org/wiki/Function_overloading

In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations.

 

Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

 

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field.

 

#include <iostream>

// volume of a cube
int volume(int s)
{
    return s*s*s;
}

// volume of a cylinder
double volume(double r, int h)
{
    return 3.14*r*r*static_cast<double>(h);
}

// volume of a cuboid
long volume(long l, int b, int h)
{
    return l*b*h;
}

int main()
{
    std::cout << volume(10);
    std::cout << volume(2.5, 8);
    std::cout << volume(100, 75, 15);

    return 0;
}

 

javascript 函数重载方法

http://www.cnblogs.com/bluedream2009/archive/2011/01/05/1925963.html

javascript不支持函数重载,不能够定义同样的函数然后通过编译器去根据不同的参数执行不同的函数。

但是javascript却可以通过自身属性去模拟函数重载。

 

如上URL提供了一种 模拟 根据函数类型, 确定执行函数的方法:

var Calculate = FunctionH.overload({
    number,number: function () {
        return arguments[0] + arguments[1];
    },
    number,number,number: function () {
        return arguments[0] * arguments[1] * arguments[2];
    }
});

alert(Calculate(1,2,3));

 

overload函数实现:

var map = function (arr, callback, pThis) {
    var len = arr.length;
    var rlt = new Array(len);
    for (var i = 0; i < len; i++) {
        if (i in arr) rlt[i] = callback.call(pThis, arr[i], i, arr); 
    }
    return rlt;
}
/**
 * 函数参数重载方法 overload,对函数参数进行模式匹配。默认的dispatcher支持*和...以及?,"*"表示一个任意类型的参数,"..."表示多个任意类型的参数,"?"一般用在",?..."表示0个或任意多个参数
 * @method overload
 * @static
 * @optional {dispatcher} 用来匹配参数负责派发的函数
 * @param {func_maps} 根据匹配接受调用的函数列表
 * @return {function} 已重载化的函数
 */
var FunctionH = {
    overload: function (dispatcher, func_maps) {
        if (!(dispatcher instanceof Function)) {
            func_maps = dispatcher;
            dispatcher = function (args) {
                var ret = [];
                return map(args, function (o) { return typeof o}).join();
            }
        } 

        return function () {
            var key = dispatcher([].slice.apply(arguments));
            for (var i in func_maps) {
                var pattern  = new RegExp("^" + i.replace("*", "[^,]*").replace("...", ".*") + "$");
                if (pattern.test(key)) {
                    return func_maps[i].apply(this, arguments);
                } 
            }
        }
    }
};

 

成熟的Javascript库实现

https://github.com/JosephClay/overload-js

Provides tools to mimic function overloading that is present in most strictly-types languages. Prevents messy, long, if-statement, type-checking functions that are hard to read and maintain. Style and API inspired by Moreiki and Mongoose.

 

例子:

var hello = (function() {

    var secret = ‘!‘;

    return overload()
        .args().use(function() {
            return secret;
        })
        .args(String).use(function(val) {
            secret = val;
        });

}());

hello(‘world‘); // calls setter
hello(); // returns ‘world‘
hello(0); // throws a Type Error

 

Detectable types

null
undefined
Infinity
Date
NaN
Number
String
Object
Array
RegExp
Boolean
Function
Element // browser only

 

javascript 函数重载 overloading

标签:asc   example   code   ram   实现   pre   url   ring   var   

原文地址:http://www.cnblogs.com/lightsong/p/6063820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!