双嵌套函数值返回停止进入双嵌套函数 [英] Double nesting a function-valued return stops from entering the double nested function
问题描述
试图理解David Shariff 的博客,我试图在这里理解闭包
Trying to understand the scope chain and execution context stack articles from David Shariff's Blog, I've tried to understand closures here
function foo() {
var a = 'private variable';
return function bar() {
alert(a);
}
}
var callAlert = foo();
callAlert(); // private variable
我只是想测试内部函数是否有变量对象只是来自其父或整个作用域链,所以我添加了一个重复示例的嵌套函数:
I just wanted to test if inner function has the variable object just from its parent or from the whole scope chain, so I added a nested function repeating the example:
function foo() {
var a = 'private variable';
return function bar() {
return function foobar() {
console.log(a);
};
};
}
var callAlert = foo();
callAlert(); //
这并没有给出任何结果.似乎解释器甚至没有进入 foobar() 函数.并且语法与其父级相同.
And that is not giving any result. It seems the interpreter is not even entering the foobar() function. And the syntax is the same than its parent.
但是如果我将函数声明和执行分开就可以了.
But it works if I divide the function declaration and execution.
function foo() {
var a = 'private variable';
return function bar() {
function ra() {
console.log(a);
};
return ra();
};
}
var callAlert = foo();
callAlert(); // private variable
我真的想猜测为什么;bar() 和 foobar() 函数的区别在哪里.
And really I'm trying to guess why; where's the difference from bar() and foobar() functions.
PS - 我正在测试 JSFiddle
PS - I'm testing on JSFiddle
推荐答案
function foo() {
var a = 'private variable';
return function bar() {
return function foobar() {
console.log(a);
};
};
}
这里你要返回一个返回函数的函数,所以你需要调用那个新的、双重嵌套的函数
Here you're returning a function that returns a function, so you need to call that new, doubly nested function
var callAlert = foo()();
或该主题的任何变体
var getBar = foo();
var getFooBar = getBar();
getFooBar(); //private variable.
第二个示例工作正常,因为您仍在返回一个函数——一个简单地调用另一个函数的函数.
The second example works fine because you're still returning one function—a function that simple calls another function.
return function bar() {
function ra() {
console.log(a);
};
return ra();
};
这篇关于双嵌套函数值返回停止进入双嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!