【发布时间】:2021-12-24 03:06:11
【问题描述】:
请注意:^ 此问题与 let/const 问题不重复,因为这无关。无论是var、let 还是const,都会保留相同的问题,因为这与问题的意图无关。
非常感谢您对另一个函数中的函数提升进行一些澄清。这是我目前清楚明白的:
这不起作用,因为anotherFunc 在创建之前在文件中被调用,而const 在创建之前没有提升。
const someFunc = () => {
console.log('someFunc called');
}
anotherFunc(); // anotherFunc is not defined error
const anotherFunc = () => {
console.log('anotherFunc called');
}
这是可行的,因为anotherFunc 是一个函数声明,它们根据 JS 规则被提升到顶部:
anotherFunc(); // anotherFunc called
function anotherFunc() {
console.log('anotherFunc called');
}
不起作用,因为它是一个函数表达式,并且由于它们被分配给var 变量,因此该变量将被提升到顶部并且最初是未定义的:
anotherFunc(); // anotherFunc is not a function at <anonymous>
var anotherFunc = function () {
console.log('anotherFunc called');
}
那么有人可以向我解释为什么这样做(见下文)吗?这比在线解释的所有内容更深入。
如果一个函数稍后声明,但在它之前的另一个函数中被调用,为什么它会起作用?这跟JS执行顺序有关系吗?
const someFunc = () => {
console.log('someFunc called');
anotherFunc();
}
const anotherFunc = () => {
console.log('anotherFunc called');
}
someFunc(); // 'someFunc called' 'anotherFunc called'
是不是因为someFunc和anotherFunc是JS先在内存中分配的,所以以后调用它们不管它们的顺序是什么?
最后,同一个场景(最后一个)中的 const/let/var 函数有区别吗?
非常感谢您的澄清!
【问题讨论】:
-
重要的是你在定义函数之后调用它。源代码中的顺序无关紧要,只是时间。
-
由于在定义了两个函数之后调用
someFunc,所以someFunc可以调用anotherFunc。 -
谢谢巴尔玛!但我想知道的更深一点。就像 JavaScript 中到底发生了什么?为什么
someFunc定义后可以调用anotherFunc? JS 是否首先将它们存储在内存中,然后当anotherFunc被调用时,它只是获得了一个已经在该内存中可用的函数?要不然是啥?事件的顺序是什么,这才是我真正好奇的。 -
function foo() { console.log(variable); } let variable = "bar"; foo(); -
重要的一点是,JavaScript 不需要在函数定义中引用它们之前声明名称。仅在引用它们的代码执行之前。
标签: javascript scope executioncontext