我试图理解为什么在执行语句后声明重复函数会影响它.
就像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) {
// };
Run Code Online (Sandbox Code Playgroud)
错误是:
未捕获的TypeError:tony.getAnswer不是函数
但是,当它运行console.log语句时,JavaScript如何知道它还不是一个函数,因为Person类直到后面的行才被覆盖console.log?
在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) {
};
Run Code Online (Sandbox Code Playgroud)
因为吊装而这样工作:
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
Run Code Online (Sandbox Code Playgroud)