0

Before I start writing this post, I already tried the codes below;

function foo(a){
    alert(a);}

function foo(a, b){
    alert(a + ' ' + b);}

And in a function which called when the page is loaded, I called the two functions as this: foo(1); foo(1, 2); Then I firstly got "1 undefined" and then "1 2".

What I expected first is that I might be able to declare the same name of functions with different parameters like Java; but I'm not sure I can. At least I'm sure that declaring function foo(a, b){...} and function foo(b, c){...} is prohibited.

0

2 Answers 2

4

JavaScript does not support function overloading

You can like this way simulate function overloading in javascript

function mother_foo(a, b) {
  if (arguments.length == 1) {
    foo(a)
  } else if (arguments.length == 2) {
   foo(a,b)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Don't allow like this.Because of this two function will be the window Object attribute.

When brower read function foo(a){},the foo will add to window Object.You can run console.log(window.log) to see the result.

Whe brower read function foo(b, c),the provious will be overwrite,You can run console.log(window.log) to see the current result.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.