对于Java闭包,我有下面的代码,非常简单,但是我试图理解闭包的复杂性,下面的代码无法按我认为的方式工作。我正在使用Node.js终端窗口(而不是console.log的浏览器)。
function init() {
let name = 'rumbo'; // i created a simple variable inside the parent function (i get this)
function displayname() {
return (name); //inner function with a **return** of the variable above (i get this also)
}
displayname(); //* see note below
}
console.log(init()); //as per my thought, this should console log 'rumbo' but it does not.
*这会显示“未定义”。 (我明白了;当您不明确声明或在外部函数上使用return / or console.log时,将得到未定义。但是,在这种情况下,displayname()函数在以下位置被调用外部函数的末尾,应该从内部函数的 return 值返回'name',但不是。
这就是我的问题,为什么外部函数调用被调用时不返回结果(在这种情况下为“ rumbo”)。
答案 0 :(得分:1)
init
不返回任何内容,因此console.log(init())
仅记录undefined
。
return
将仅 返回当前正在执行的函数的值-不会return
一直到调用堆栈中的所有当前正在执行的函数。 (毕竟,这太混乱了,几乎无法使用。)因此,您必须在return name
内displayname
,以便displayname
返回一些信息。但是然后您希望init
的调用者接收该值,因此init
也必须使用return
来return displayname()
。
答案 1 :(得分:0)
主要是因为您没有告诉它返回值。除非您告诉函数返回其他内容,否则该函数将返回undefined
。
如果您改为这样做...
function init() {
let name = 'rumbo'; // i created a simple variable inside the parent function (i get this)
function displayname() {
return (name); //inner function with a **return** of the variable above (i get this also)
}
return displayname(); //* see note below
}
console.log(init()); //as per my thought, this should console log 'rumbo' but it does not.
您将得到您期望的结果。
您也可以这样想...
function init() {
let name = 'rumbo'; // i created a simple variable inside the parent function (i get this)
function displayname() {
return (name); //inner function with a **return** of the variable above (i get this also)
}
const x = displayname();
return x;
}
console.log(init()); //as per my thought, this should console log 'rumbo' but it does not.