[英]Why inside a function you can use a variable that's declared later
I was writing a Dialog component and this thought came into my mind suddenly.我正在写一个对话框组件,这个想法突然出现在我的脑海中。
export const alert = (content: string) => {
const buttons = [<button onClick={()=>closeModal()}>ok</button>] // quite ok
// const buttons = [<button onClick={closeModal}>ok</button>] // raise an error
const closeModal = modal(content, buttons)
}
The error is: Block-scoped variable 'closeModal' used before its declaration.错误是:在声明之前使用了块范围变量“closeModal”。 I am so used to wrap some expression in a function in React and never thought about it.
我习惯于在 React 中的 function 中包装一些表达式,但从未想过。
The situation may be simplified to below:情况可以简化为以下:
const caller = () => {
func() // ok
}
const funcAgain = func // error
func() // error
const func = () => {}
What's this behavior called?这种行为叫什么? Does it have something to do with closure?
跟闭包有关系吗? or variable hoisting?
还是可变提升?
This has to do with the basics of The variable declaration and scope management and then execution phase.这与变量声明和 scope 管理和执行阶段的基础有关。 Here variable declarations for blocked scope variables(let, const), are actually hoisted but not initialised.
此处阻塞的 scope 变量(let,const)的变量声明实际上被提升但未初始化。 Js engine simply denies any operation on uninitialized variable identifiers.
Js 引擎简单地拒绝对未初始化的变量标识符的任何操作。
Also there is famous term for this called as Temporal Dead Zone(TDZ).还有一个著名的术语称为时间死区(TDZ)。 func is in its TDZ in this case.
在这种情况下,func 位于其 TDZ 中。
Hope this helps.希望这可以帮助。
Good question.好问题。 onClick on the first sample works because it returns a new Function object.
第一个样本上的 onClick 有效,因为它返回一个新的 Function object。 The body of the function does not get evaluated until it is being invoked.
function 的主体在被调用之前不会被评估。
()=>closeModal()
I think you are referring to 'Hoisting'.我认为您指的是“吊装”。 To hoist a function, you need to declare as below
要吊装 function,您需要声明如下
const caller = () => {
func() // ok
}
func()
function func () {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.