How does Javascript execute code when duplicate named functions are declared?

[亡魂溺海] 提交于 2019-12-31 04:15:09

问题


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 placement/control flow, and then executing console.log expressions. Example:

function Question(x, y) {
   this.getAnswer = function() {
  return 42;
  };
};

var tony = new Question('Stack','Overflow');
console.log(tony.getAnswer());   // 42, as expected.

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

The error is:

Uncaught TypeError: tony.getAnswer is not a function

But how does JavaScript know it's not a function yet when it's running the console.log statement, since the Person class doesn't get overwritten until the line after the console.log?


回答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:

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



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



来源:https://stackoverflow.com/questions/31714283/how-does-javascript-execute-code-when-duplicate-named-functions-are-declared

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!