Javascript 返回函数的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7629891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Functions that return a function
提问by Cafecorridor
I'm stuck with this concept of 'Functions that return functions'. I'm referring the book 'Object Oriented Javascript' by Stoyan Stefanov.
我坚持“返回函数的函数”这个概念。我指的是 Stoyan Stefanov 所著的“面向对象的 Javascript”一书。
Snippet One:
片段一:
function a() {
alert('A!');
function b(){
alert('B!');
}
return b();
}
var s = a();
alert('break');
s();
Output:
输出:
A!
B!
break
Snippet Two
片段二
function a() {
alert('A!');
function b(){
alert('B!');
}
return b;
}
var s = a();
alert('break');
s();
A!
break
B!
Can someone please tell me the difference between returning b
and b()
in the above snippets?
有人可以告诉我返回b
和b()
上述片段之间的区别吗?
回答by kzh
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.
将变量分配给函数(不带括号)会复制对函数的引用。将括号放在函数名的末尾,调用函数,返回函数的返回值。
Demo
演示
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'
The function is still callable. It still exists. This is used in JavaScript all the time. Functions can be passed around justlike other values. Consider the following:
该函数仍然是可调用的。它仍然存在。这一直在 JavaScript 中使用。函数可以绕过只是像其他值。考虑以下:
function counter() {
var count = 0;
return function() {
alert(count++);
}
}
var count = counter();
count();
count();
count();
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.
函数 count 可以保留在其外部定义的变量。这称为闭包。它在 JavaScript 中也被大量使用。
回答by Michael Berkowski
Returning the function name without ()
returns a reference to the function, which can be assigned as you've done with var s = a()
. s
now contains a reference to the function b()
, and calling s()
is functionally equivalent to calling b()
.
返回函数名而不()
返回对函数的引用,可以像使用var s = a()
. s
现在包含对函数的引用b()
,并且调用s()
在功能上等同于调用b()
。
// Return a reference to the function b().
// In your example, the reference is assigned to var s
return b;
Calling the function with ()
in a return statement executes the function, and returns whatever value was returned by the function. It is similar to calling var x = b();
, but instead of assigning the return value of b()
you are returning it from the calling function a()
. If the function b()
itself does not return a value, the call returns undefined
after whatever other work is done by b()
.
()
在 return 语句中调用该函数会执行该函数,并返回该函数返回的任何值。它类似于调用var x = b();
,但不是分配返回值,b()
而是从调用函数返回它a()
。如果函数b()
本身不返回值,则调用undefined
在 完成任何其他工作后返回b()
。
// Execute function b() and return its value
return b();
// If b() has no return value, this is equivalent to calling b(), followed by
// return undefined;
回答by Abdo
return b();
calls the function b(), and returns its result.
return b();
调用函数 b(),并返回其结果。
return b;
returns a reference to the function b, which you can store in a variable to call later.
return b;
返回对函数 b 的引用,您可以将其存储在变量中以供以后调用。
回答by Cheeso
Returning b
is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.
返回b
是返回一个函数对象。在 Javascript 中,函数只是对象,就像任何其他对象一样。如果您觉得这没有帮助,只需将“对象”一词替换为“事物”即可。您可以从函数返回任何对象。您可以返回真/假值。一个整数 (1,2,3,4...)。您可以返回一个字符串。您可以返回具有多个属性的复杂对象。你可以返回一个函数。函数只是一个东西。
In your case, returning b
returns the thing, the thing is a callable function. Returning b()
returns the value returned by the callable function.
在您的情况下,返回b
返回事物,事物是一个可调用的函数。返回b()
返回可调用函数返回的值。
Consider this code:
考虑这个代码:
function b() {
return 42;
}
Using the above definition, return b();
returns the value 42. On the other hand return b;
returns a function, that itself returns the value of 42. They are two different things.
使用上面的定义,return b();
返回值 42。另一方面,return b;
返回一个函数,它本身返回值 42。它们是两个不同的东西。
回答by vzwick
When you return b
, it is just a reference to function b, but not being executed at this time.
当你 return 时b
,它只是对函数 b 的引用,但此时并没有被执行。
When you return b()
, you're executing the function and returning its value.
当您 return 时b()
,您正在执行该函数并返回其值。
Try alert
ing typeof(s)
in your examples. Snippet b will give you 'function'. What will snippet a give you?
尝试alert
荷兰国际集团typeof(s)
在您的例子。代码段 b 会给你“功能”。片段会给你什么?
回答by Francesco Belladonna
Imagine the function as a type, like an int. You can return ints in a function. You can return functions too, they are object of type "function".
把函数想象成一种类型,就像一个 int。您可以在函数中返回整数。您也可以返回函数,它们是“函数”类型的对象。
Now the syntax problem: because functions returns values, how can you return a function and not it's returning value?
现在是语法问题:因为函数返回值,你怎么能返回一个函数而不是它的返回值?
by omitting brackets! Because without brackets, the function won't be executed! So:
通过省略括号!因为没有括号,函数不会被执行!所以:
return b;
Will return the "function" (imagine it like if you are returning a number), while:
将返回“函数”(想象一下,如果您正在返回一个数字),同时:
return b();
First executes the function thenreturn the value obtained by executing it, it's a big difference!
先执行函数再返回执行得到的值,差别很大!
回答by Shaz
Create a variable:
创建一个变量:
var thing1 = undefined;
Declare a Function:
声明一个函数:
function something1 () {
return "Hi there, I'm number 1!";
}
Alert the valueof thing1
(our first variable):
警报的值的thing1
(我们的第一个变量):
alert(thing1); // Outputs: "undefined".
Now, if we wanted thing1
to be a referenceto the function something1
, meaning it would be the same thing as our created function, we would do:
现在,如果我们想thing1
成为对 function的引用something1
,这意味着它与我们创建的函数是一样的,我们会这样做:
thing1 = something1;
However, if we wanted the return
valueof the function then we must assign it the return value of the executed function. You execute the function by using parenthesis:
但是,如果我们想要函数的return
值,那么我们必须为它分配执行函数的返回值。使用括号执行函数:
thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!"
回答by Zilvinas
This is super useful in real life.
这在现实生活中非常有用。
Working with Express.js
使用 Express.js
So your regular express
route looks like this:
所以你的常规express
路线是这样的:
function itWorksHandler( req, res, next ) {
res.send("It works!");
}
router.get("/check/works", itWorksHandler );
But what if you need to add some wrapper, error handler or smth?
但是如果您需要添加一些包装器、错误处理程序或 smth 怎么办?
Then you invoke your function off a wrapper.
然后您从包装器中调用您的函数。
function loggingWrapper( req, res, next, yourFunction ) {
try {
yourFunction( req, res );
} catch ( err ) {
console.error( err );
next( err );
}
}
router.get("/check/works", function( req, res, next ) {
loggingWrapper( req, res, next, itWorksHandler );
});
Looks complicated? Well, how about this:
看起来很复杂?嗯,这个怎么样:
function function loggingWrapper( yourFunction ) => ( req, res, next ) {
try {
yourFunction( req, res, next );
} catch ( err ) {
console.error( err );
next( err );
}
}
router.get("/check/works", loggingWrapper( itWorksHandler ) );
See at the end you're passing a function loggingWrapper
having one argument as another function itWorksHandler
, and your loggingWrapper
returns a new function which takes req, res, next
as arguments.
最后看到您将一个loggingWrapper
具有一个参数的函数作为另一个函数传递itWorksHandler
,并且您loggingWrapper
返回一个新函数req, res, next
作为参数。