JavaScript function overloading overloading

Source: Internet
Author: User

function overloading

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

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

Calls to an overloaded function would 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) is overloaded methods. To call the latter, an object must being passed as a parameter, whereas the former does not require a parameter, and is Calle D 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 (ten);    Std::cout << Volume (2.5, 8);    Std::cout << Volume (+,-);    return 0;}

JavaScript function Overloading method

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

JavaScript does not support function overloading, it is not possible to define the same function and then use the compiler to perform different functions according to different parameters.

But JavaScript can use its own properties to simulate function overloading.

The above URL provides a way to simulate the execution of a function based on the type of function:

varCalculate =Functionh.overload ({'Number,number': Function () {returnarguments[0] + arguments[1]; },    'Number,number,number': Function () {returnarguments[0] * arguments[1] * arguments[2]; }); alert (Calculate (1,2,3));

Overload function Implementation:

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;} /** * Function Parameter overloading method overload, the function parameters are pattern-matched. The default dispatcher support * and ... and?, "*" denotes an arbitrary type of argument, "..." means more than one parameter of any type, "?" Generally used in ",?..." means 0 or any number of parameters * @method overload * @static * @optional {Dispatcher} is used to match parameters assigned to the function * @param {func_maps} to accept the call according to the letter List of tables * @return {function} overloaded functions */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= newRegExp ("^" + i.replace ("*", "[^,]*"). Replace ("...", ". *") + "$");                if (Pattern.test (key)) {return func_maps[i].apply (this, arguments); }             }        }    }};

A mature JavaScript library implementation

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

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

Example:

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
NullundefinedInfinityDateNaNnumberStringObjectArrayRegExpBoolean  Function//Browser            only

JavaScript function overloading overloading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.