当声明重复的命名函数时,Javascript如何执行代码?
我试图理解为什么在语句执行后声明重复函数会影响它 这就好像JavaScript首先读取所有函数,而不考虑位置/控制流,然后执行console.log表达式。例如:当声明重复的命名函数时,Javascript如何执行代码?,javascript,object,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
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不是函数
但是当JavaScript运行console.log语句时,它怎么知道它还不是一个函数呢?因为Person类直到console.log后面的那一行才被覆盖?在JavaScript中,如果定义了两个同名函数,那么最后一个解析的函数就是解析后将被激活的函数。第一个将被第二个取代,而且无法到达第一个 另外,请记住,一个作用域中的所有函数{}定义都被提升到作用域的顶部,并在该作用域中的任何代码执行之前进行处理。因此,在您的示例中,如果您取消注释第二个定义,它将是整个作用域的有效定义,因此您的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
在Javascript中,如果定义了两个同名函数,那么最后一个解析的函数就是解析后激活的函数。第一个将被第二个取代,而且无法到达第一个 另外,请记住,一个作用域中的所有函数{}定义都被提升到作用域的顶部,并在该作用域中的任何代码执行之前进行处理。因此,在您的示例中,如果您取消注释第二个定义,它将是整个作用域的有效定义,因此您的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
它被称为提升,所有声明性函数和变量声明都在编译时上移,尽管未定义 声明函数是如下函数
函数名{…}它被称为提升,所有声明性函数和变量声明都在编译时上移,尽管未定义 声明函数是如下函数 函数名{…}