Misha Moroshko
Misha Moroshko

Reputation: 171321

Very basic Javascript constructors problem

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();
}

Upvotes: 1

Views: 163

Answers (3)

deceze
deceze

Reputation: 522005

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.

Upvotes: 0

Dustin
Dustin

Reputation: 1966

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).

Upvotes: 1

SLaks
SLaks

Reputation: 887225

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);
}

Upvotes: 7

Related Questions