我知道在JavaScript中只有函数声明会被提升,这意味着在运行函数sum后应该打印出30。
然而它显示diff未定义,它不应该被提升吗?
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
let diff = function(x, y) {
return x - y;
}
我知道在JavaScript中只有函数声明会被提升,这意味着在运行函数sum后应该打印出30。
然而它显示diff未定义,它不应该被提升吗?
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
let diff = function(x, y) {
return x - y;
}
正如您所说,只有函数声明会被提升,而不是函数表达式(将无名函数分配给变量)。以下代码可行:
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
function diff(x, y) {
return x - y;
}
To declare diff
the way you did, you must lift it to the top of your code:
let diff = function(x, y) {
return x - y;
}
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
函数表达式
不像函数声明
那样会被提升。
JavaScript中的函数表达式不会被提升,不同于函数声明。您不能在创建它们之前使用函数表达式:
console.log(notHoisted) // undefined
// even though the variable name is hoisted, the definition isn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
函数声明
如果你希望它被提升。是的,let和const会被提升,但在运行时实际声明被评估之前,您无法访问它们。
let
和const
声明会被提升,但它们的定义会保留在原地。与您所说的基本思路相同,但我想更加精确。 - JAAulde在初始化函数之前访问该函数。
这样应该可以工作,
let diff = function(x, y) {
return x - y;
}
function sum(x, y) {
return x + y;
}
console.log(sum(10, 20));
console.log(diff(10, 20));
let diff 会被提升,但是当函数 diff(10, 20); 被调用时,变量 diff 还没有被定义为函数。
请在 Google 上搜索此主题:函数声明 vs 函数表达式。
sum
和diff
在顶部被声明,然后定义sum
,进行调用,_然后_定义diff
(因为你使用了let
,所以该定义留在调用之后)。所以你是在定义之前调用。 - JAAulde