What happens if I declare two variables with the same name and scope?
var foo = (function() {
return {
alertMe: function() {
alert("foo1");
}
}
})();
var foo = (function() {
return {
alertMe: function() {
alert("foo2");
}
}
})();
foo.alertMe();
I'm asking because I'm dynamically loading little portlets on my website and each portlet has its own script tag with a JavaScript module. The problem is, users can duplicate portlets which means there is a good chance something like the above may happen.
In your example they're both undefined anyway, so you'll have a value of undefined
.
Anyway, the second var
is ignored. You'll have the same result as though you didn't have it, meaning foo
will be overwritten with the new value.
So, same result as if you did:
var foo = (function() {
alert("foo1");
})();
foo = (function() { // I'm overwriting the value of "foo"
alert("foo2");
})();
EDIT: The code in the question changed. The result is now more observable if you run the code. The foo
variable's reference to the first object is replaced with a reference to the second. The first reference is lost.