I\'m trying to understand why declaring a duplicate function after a statement has executed affects it.
It\'s as if JavaScript is reading ALL functions first,
In Javascript, if you define two functions with the same name, then the last one parsed is the one that will be active after parsing. The first one will be replaced by the second one and there will be no way to reach the first one.
Also, keep in mind that all function() {}
definitions within a scope are hoisted to the top of the scope and are processed before any code in that scope executes so in your example, if you uncomment the second definition, it will be the operative definition for the entire scope and thus your var tony = new Question('Stack','Overflow');
statement will use the 2nd definition which is why it won't have a .getAnswer()
method.
So, code like this:
function Question(x, y) {
this.getAnswer = function() {
return 42;
};
};
var tony = new Question('Stack','Overflow');
console.log(tony.getAnswer());
// If the following 2 lines are uncommented, I get an error:
function Question(x, y) {
};
Works like this because of hoisting:
function Question(x, y) {
this.getAnswer = function() {
return 42;
};
};
// If the following 2 lines are uncommented, I get an error:
function Question(x, y) {
};
var tony = new Question('Stack','Overflow');
console.log(tony.getAnswer()); // error
It's called Hoisting, all declarative functions and variable declarations are moved up, though undefined, at compilation.
http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092
http://bonsaiden.github.io/JavaScript-Garden/#function.scopes
declarative function are functions like
function name(){...}