views:

59

answers:

3

Hi,

In the following JavaScript code main() is called. My question is why the second constructor is called rather than the first one ? What am I missing here ?

Thanks !!

function AllInputs() {
   alert("cons 1");
   this.radioInputs = [];
   alert(this);
}

function AllInputs(radioElement) {
   alert("cons 2");
   this.radioInputs = [radioElement];
   alert(this);
}

AllInputs.prototype.toString = function() {
   return "[object AllInputs: radioInputs: " + this.radioInputs.length + "]";
}

function main() {
   var result = new AllInputs();
}
+7  A: 

Javascript does not support overloaded functions.

When you define the same function twice, the second definition replaces the first one.

Instead, you should make a single function, and check arguments.length to see how many arguments were passed.

For example:

function AllInputs(radioElement) {
   this.radioInputs = arguments.length ? [radioElement] : [];
   alert(this);
}
SLaks
Thanks for the explanation !
Misha Moroshko
A: 
function foo() { ... }

is really just shorthand for

var foo = function () { ... }

Hence, the second time you're declaring the function, you're overwriting the variable AllInputs with a different function. There ain't no such thing as two functions with the same name in Javascript, since all functions are really variables.

deceze
Actually, they're not quite the same.
SLaks
@SLaks Then maybe "they handle like variables"?
deceze
+1  A: 

In JavaScript, the last definition of an identifier is used:

function foo() { return "bar"; }
var foo = "foo";

alert(foo);

In that case, foo was a variable with the value "foo". Had foo been a function, it would have simply said that foo was a function. If you don't believe it, try using alert(foo()) instead of just alert(foo). You'll most likely get an error in your console log with no visible output like you had with alert(foo) (the variable...not the function call).

Dustin