Last active
November 15, 2020 22:51
-
-
Save cihat/7e2ea41b9075a653ab780858a96abf95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
overloading | |
Most object-oriented languages support function overloading, which is the | |
ability of a single function to have multiple signatures. A function signature | |
is made up of the function name plus the number and type of parameters | |
the function expects. Thus, a single function can have one signature that | |
accepts a single string argument and another that accepts two numeric | |
arguments. The language determines which version of a function to call | |
based on the arguments that are passed in. | |
As mentioned previously, JavaScript functions can accept any number | |
of parameters, and the types of parameters a function takes aren’t speci- | |
fied at all. That means JavaScript functions don’t actually have signatures. | |
A lack of function signatures also means a lack of function overloading. | |
Look at what happens when you try to declare two functions with the | |
same name: | |
function sayMessage(message) { | |
console.log(message); | |
} | |
function sayMessage() { | |
console.log("Default message"); | |
} | |
sayMessage("Hello!"); // outputs "Default message" | |
If this were another language, the output of sayMessage("Hello!") would | |
likely be "Hello!". In JavaScript, however, when you define multiple func- | |
tions 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. | |
function sayMessage(message) { | |
if (arguments.length === 0) { | |
message = "Default message"; | |
} | |
console.log(message); | |
} | |
sayMessage("Hello!"); // outputs "Hello!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment