JavaScript Function Overloading

原创转载请注明出处:http://agilestyle.iteye.com/blog/2341742

Function Overloading

A function signature is made up of the function name plus the number and type of parameters the function expects. JavaScript functions can accept any number of parameters, and the types of parameters a function takes aren’t specified at all. That means JavaScript functions don’t actually have signatures. A lack of function signatures also means a lack of function overloading. For example:

function sayMessage(message) {
    console.log(message);
}

function sayMessage() {
    console.log("Default message");
}

sayMessage("Hello!");       // outputs "Default message"

In JavaScript when you define multiple functions with the same name, the one that appears last in your code wins.The earlier function declarations are completely removed, and the last is the one that is used. Once again, it helps to think about this situation using objects:

var sayMessage = new Function("message", "console.log(message);");
sayMessage = new Function("console.log(\"Default message\");");
sayMessage("Hello!");       // outputs "Default message"

Looking at the code this way makes it clear why the previous code didn't work. A function object is being assigned to sayMessage twice in a row, so it makes sense that the first function object would be lost.

The fact that functions don't have signatures in JavaScript doesn't mean you can't mimic function overloading. You can retrieve the number of parameters that were passed in by using the arguments object, and you can use that information to determine what to do. For example:

function sayMessage(message) {
    if (arguments.length === 0) {
        message = "Default message";
    }
    console.log(message);
}
sayMessage("Hello!");       // outputs "Hello!"

Note:

In practice, checking the named parameter against undefined is more common than relying on arguments.length

Reference

Leanpub.Principles.of.Object-Oriented.Programming.in.JavaScript.Jun.2014