javascript 函數重載 overloading

來源:互聯網
上載者:User

標籤: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 cubeint volume(int s){    return s*s*s;}// volume of a cylinderdouble volume(double r, int h){    return 3.14*r*r*static_cast<double>(h);}// volume of a cuboidlong 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 setterhello(); // returns ‘world‘hello(0); // throws a Type Error

 

Detectable types
nullundefinedInfinityDateNaNNumberStringObjectArrayRegExpBooleanFunctionElement // browser only

 

javascript 函數重載 overloading

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.