gpt4 book ai didi

javascript - 为什么我可以在它在 javascript 中声明之前返回一个函数?

转载 作者:行者123 更新时间:2023-11-29 16:57:05 25 4
gpt4 key购买 nike

为什么下面的工作:

function outsideFunction() {
return {
insideFunction: insideFunction
}

function insideFunction() {
...stuff
}
}

不是

function insideFunction() {
...stuff
}

一样
var insideFunction = function() { ...stuff }

哪个会导致 var insideFunction 被提升到顶部?insideFunction 在对象声明中使用时不应该返回 undefined 吗?

我可以对一个对象做同样的事情吗?换句话说,我可以这样做吗:

return {objectName: objectName}
var objectName = {}

最佳答案

这是因为提升 - 在您声明它们之前可以访问事物,因为所有声明都“提升”到您的范围的顶部。你说:

isn't

function insideFunction() {
...stuff
}

the same as

var insideFunction = function() { ...stuff }

没有。根据 the MDN documentation :

Function declarations in JavaScript are hoisting the function definition. You can use the function before you declared it:

hoisted(); // logs "foo"

function hoisted() {
console.log("foo");
}

Note that function expressions are not hoisted:

notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function() {
console.log("bar");
};

最后一个问题:

can I do:

return {objectName: objectName}
var objectName = {}

同样,不。虽然 objectName 将被声明(因此您可以避免引用错误),但它在您返回时的值将是 undefined

关于javascript - 为什么我可以在它在 javascript 中声明之前返回一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com