Very basic Javascript constructors problem
In the following JavaScript code main() i开发者_开发知识库s 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();
}
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);
}
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).
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.
精彩评论