[英]Why can you reference a variable before declaring it in a function property of an object?
Basically, I'm looking for an explanation of why and how this is working基本上,我正在寻找关于为什么以及如何工作的解释
const someObj = {
test: () => callback()
}
const callback = () => console.log("how?")
someObj.test()
output: how?
and this is not这不是
const someObj = {
test: callback()
}
const callback = () => console.log("how?")
someObj.test
output: Uncaught ReferenceError: Cannot access 'callback' before initialization
In your first example you are assigning a function to the property test.在您的第一个示例中,您将 function 分配给属性测试。 It doesn't try to call callback until you call it.
在您调用它之前,它不会尝试调用回调。 By the time you do call it callback has been defined.
当你调用它的时候,回调已经被定义了。 Try calling test before you define callback and you will see if also fails.
在定义回调之前尝试调用测试,你会看到是否也会失败。
In your second example you are trying to assign the result of calling callback to the property test, but seeing callback hasn't been defined yet you get the error.在您的第二个示例中,您尝试将调用回调的结果分配给属性测试,但看到尚未定义回调,您会收到错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.