声明重复的命名函数时,Javascript 如何执行代码? [英] How does Javascript execute code when duplicate named functions are declared?

查看:61
本文介绍了声明重复的命名函数时,Javascript 如何执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand why declaring a duplicate function after a statement has executed affects it.

就好像 JavaScript 首先读取所有函数,而不考虑放置/控制流,然后执行 console.log 表达式.示例:

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

错误是:

未捕获的类型错误:tony.getAnswer 不是函数

Uncaught TypeError: tony.getAnswer is not a function

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

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?

推荐答案

在 Javascript 中,如果定义了两个同名的函数,那么最后一个解析的就是解析后激活的那个.第一个会被第二个取代,第一个就没有办法到达了.

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.

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

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.

所以,代码如下:

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

这篇关于声明重复的命名函数时,Javascript 如何执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆