简体   繁体   English

为什么在 object 的 function 属性中声明变量之前可以引用它?

[英]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.

相关问题 为什么要为变量分配一个函数而不是声明一个命名函数? - Why would you assign a function to a variable instead of declaring a named function? 为什么函数变量不能具有对象属性而数字变量不能具有对象属性? - Why does function variable can have object property and number variable not? 为什么我可以在 JavaScript / TypeScript 中声明变量之前使用它? - Why can I use a variable before declaring it in JavaScript / TypeScript? 通过传递变量引用对象的函数属性 - Reference a function property of object by passed variable 如何在for循环中添加迭代器的变量,以引用javascript对象中的数字属性? - How can you add the variable of an iterator in a for loop to reference a numeric property in an object in javascript? 在解构赋值之前声明对象属性类型 - Declaring object property types before destructuring assignment 为什么不将变量声明为函数的参数? - Why not declaring a variable as an argument of a function? 为什么我可以在分配给对象常量中相同变量的变量中使用变量,但是却在函数常量中创建自引用? - Why can I use a variable in an assignment to that same variable in an object literal, but it creates a self-reference in a function literal? 使用不起作用的函数声明javascript对象属性 - declaring javascript object property with a function not working 为什么可以在内部函数成员中访问对象引用,而不是在内部属性成员中访问? - Why can an object reference be accessed in inner function members but not in inner property members?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM