Very simple problem with Javascript constructors

The following JavaScript calls the main () code. My question is, why is the second constructor called and not the first? What am I missing here?

Thank!

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

      

+2


a source to share


3 answers


Javascript doesn't support overloaded functions.

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

Instead, you should make one function and check arguments.length

to see how many arguments were passed.



For example:

function AllInputs(radioElement) {
   this.radioInputs = arguments.length ? [radioElement] : [];
   alert(this);
}

      

+7




JavaScript uses the last definition of an identifier:

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

alert(foo);

      



In this case, it foo

was a variable with the value "foo". If it foo

was a function, it would simply say what it foo

is. If you don't believe it, try using alert(foo())

instead alert(foo)

. You will most likely get an error in your console log with no visible output like you do with alert(foo)

(variable ... not a function call).

+1


a source


function foo() { ... }

      

is actually just shorthand for

var foo = function () { ... }

      

Hence, the second time you declare a function, you are overwriting the variable with AllInputs

another function. There is no such function in Javascript like two functions with the same name, since all functions are truly variables.

0


a source







All Articles