Skip to content Skip to sidebar Skip to footer

How Does Javascript Execute Code When Duplicate Named Functions Are Declared?

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, regardless of placemen

Solution 1:

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:

functionQuestion(x, y) {
   this.getAnswer = function() {
  return42;
  };
};

var tony = newQuestion('Stack','Overflow');
console.log(tony.getAnswer());

// If the following 2 lines are uncommented, I get an error:functionQuestion(x, y) { 
};

Works like this because of hoisting:

functionQuestion(x, y) {
   this.getAnswer = function() {
  return42;
  };
};

// If the following 2 lines are uncommented, I get an error:functionQuestion(x, y) { 
};

var tony = newQuestion('Stack','Overflow');
console.log(tony.getAnswer());    // error

Solution 2:

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(){...}

Post a Comment for "How Does Javascript Execute Code When Duplicate Named Functions Are Declared?"