返回函数的函数 [英] Functions that return a function
问题描述
我坚持使用'返回函数的函数'这个概念。我指的是Stoyan Stefanov撰写的面向对象的Javascript一书。
I'm stuck with this concept of 'Functions that return functions'. I'm referring the book 'Object Oriented Javascript' by Stoyan Stefanov.
Snippet One:
function a() {
alert('A!');
function b(){
alert('B!');
}
return b();
}
var s = a();
alert('break');
s();
输出
A!
B!
break
Snippet Two
function a() {
alert('A!');
function b(){
alert('B!');
}
return b;
}
var s = a();
alert('break');
s();
输出:
A!
break
B!
有人可以告诉我返回 b $ c $之间的区别c>和
b()
在上面的片段中?
Can someone please tell me the difference between returning b
and b()
in the above snippets?
推荐答案
分配函数的变量(没有括号)复制对函数的引用。将括号放在函数名的末尾,调用函数,返回函数返回值。
Assigning a variable to a function (without the parenthesis) copies the reference to the function. Putting the parenthesis at the end of a function name, calls the function, returning the functions return value.
function a() {
alert('A');
}
//alerts 'A', returns undefined
function b() {
alert('B');
return a;
}
//alerts 'B', returns function a
function c() {
alert('C');
return a();
}
//alerts 'C', alerts 'A', returns undefined
alert("Function 'a' returns " + a());
alert("Function 'b' returns " + b());
alert("Function 'c' returns " + c());
在您的示例中,您还在函数中定义函数。如:
In your example, you are also defining functions within a function. Such as:
function d() {
function e() {
alert('E');
}
return e;
}
d()();
//alerts 'E'
该功能仍可调用。它仍然存在。这在JavaScript中一直使用。函数可以像其他值一样在 周围传递。请考虑以下事项:
The function is still callable. It still exists. This is used in JavaScript all the time. Functions can be passed around just like other values. Consider the following:
function counter() {
var count = 0;
return function() {
alert(count++);
}
}
var count = counter();
count();
count();
count();
函数计数可以保留在其外部定义的变量。这称为闭包。它在JavaScript中也经常使用。
The function count can keep the variables that were defined outside of it. This is called a closure. It's also used a lot in JavaScript.
这篇关于返回函数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!