当声明重复的命名函数时,Javascript如何执行代码?

时间:2015-07-30 02:32:59

标签: javascript object

我试图理解为什么在语句执行后声明重复的函数会影响它。

好像JavaScript首先读取所有函数,无论放置/控制流如何,然后执行console.log表达式。例如:

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) { 
// };

错误是:

  

未捕获的TypeError:tony.getAnswer不是函数

但是,当JavaScript运行console.log语句时,JavaScript如何知道它还不是一个函数,因为Person类在行之前不会被覆盖之后 console.log

2 个答案:

答案 0 :(得分:6)

在Javascript中,如果您定义两个具有相同名称的函数,则解析的最后一个函数将是解析后将处于活动状态的函数。第一个将被第二个替换,将无法到达第一个。

另外,请记住,作用域中的所有function() {}定义都会被提升到作用域的顶部,并在该作用域中的任何代码执行之前进行处理,因此在您的示例中,如果取消注释第二个定义,则将是整个范围的有效定义,因此您的var tony = new Question('Stack','Overflow');语句将使用第二个定义,这就是为什么它没有.getAnswer()方法。

所以,代码如下:

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) { 
};

因为吊装而这样工作:

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

答案 1 :(得分:0)

它被称为Hoisting,所有声明性函数和变量声明在编译时都会向上移动,虽然未定义。

http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092

http://bonsaiden.github.io/JavaScript-Garden/#function.scopes

声明性函数是

之类的函数

function name(){...}