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.

Yeongchan Jeon
  • 499
  • 3
  • 18

2 Answers2

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)
  }
}
ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
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.

Ying Yi
  • 784
  • 4
  • 16