javascript 函数重载 overloading

本文介绍了函数重载的概念及其在C++和JavaScript中的实现方法。在C++中,通过定义具有相同名称但参数列表不同的多个函数来实现重载;而在JavaScript中,则通过模拟的方式实现函数重载,提供了一个实用的函数重载实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数重载

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值