Node JS匿名函数和回调 [英] Node JS anonymous functions and callbacks

查看:165
本文介绍了Node JS匿名函数和回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人请帮助我。我一直在阅读大量的javascript文档和摆弄javascript。

Someone please help me. I have been reading a lot of javascript documentation and fiddling with javascript.

我能够使用这些函数,但我不太会在这里找到这个必要的句法爵士乐

I am able to use the functions but I don't quite get this essential syntactic jazz going on here

          var http = require('http');
          http.createServer(function (req, res) {
                 res.writeHead(200, {'Content-Type': 'text/plain'});
                 res.end('Hello World\n');
          }).listen(1337, 'myhost');

          console.log('Server running at http://myhost:1337/');

我无法弄清楚为什么可以在上面的匿名函数中使用req和res。这就像他们住在http里面的某个地方。他们没有在任何地方宣布!它们在引用内部对象或其他内容的匿名函数中组成变量名。这很疯狂。

I cant figure out why its okay to use req and res in the anonymous function above. It's like they live somewhere inside of http. They are not declared anywhere! They are made up variable names in an anonymous function that reference inner objects or something. It's crazy.

回调功能如何?

或类似

          stream.on('data', function(data){  
                //  use data... i dont know where its coming from 
                //  or how it got there, but use it
          });

如果你可以发布一个模仿这个过程和语法的小例子,或解释这些回调函数如何工作像这样或如何将这些未声明的变量传递给这样的函数我会非常感激。

If you could post a small example that mimics this process and syntax or explain how these callback functions can work like this or how I can pass these undeclared variables into functions like this I would greatly appreciate it.

下面发布的答案的类似示例。

A similar example to the answer posted below.

     var b = {                  
           somefunction : function( data ){
                 var x = 100;
                 x = x+1;        // 101

                 return data(x); // returns the callback function data w/ value x
           } 
     };

     b.somefunction(function(foo){
           foo++;                // 101 + 1
           console.log(foo);     // prints 102
     });


推荐答案

主要问题是Javascript是一种功能语言所以您可以将函数作为参数传递给其他函数。例如,在其他语言中,您可能经历过将指针或句柄传递给函数。考虑一下你有一些数学函数的简单情况:

The main issue is that Javascript is a functional language so you can pass functions as parameters to other functions. In other languages you may have experienced passing a pointer or handle to a function, for example. Consider a simple cases in which you have some math functions:

function add(a,b) {return (a+b)};
function subtract(a,b) {return (a-b)}:

现在我可以创建一个新函数:

Now I could create a new function:

function longWayAroundTheBarn(num1,num2,theFunc)
{
    // invoke the passed function with the passed parameters
    return theFunc(num1,num2);
}

并将其称为:

console.log(longWayAroundTheBarn(1,2),add);

> 3

或者甚至是这样:

console.log(longWayAroundTheBarn(longWayAroundTheBarn(2,2,subtract),4,add);

> 4

显然这将是一个愚蠢的使用回调,但你可以想象一下,以这种方式'插入'一个功能的能力可以非常强大。

Obviously this would be a silly use callbacks, but you can imagine generally that the ability to 'plug-in' a function this way can be pretty powerful.

考虑一下您是否无法传递函数。这可能是您实现此目的的一种方式:

Consider if you couldn't pass functions. This might be one way you would implement this:

function reallyLongWayAround(num1,num2,funcName)
{
    if(funcName==='add')
        return add(num1 ,num2);
    else if (funcName === 'subtract')
        return subtract(num1, num2);
}

你可以想象,除了必须编写和维护真正乏味的代码之外,它还不是那么强大,因为 reallyLongWayAround 函数只能永远调用它知道的代码。通过传递函数,我的 longWayAroundTheBarn 并不关心我是否创建新函数并将其传递给它。请注意,由于键入较弱,它甚至不需要关心它传递的参数。也许你想实现类似

You can imagine that besides being really tedious code to have to write and maintain, it's not nearly so powerful because the reallyLongWayAround function could only ever call code it knew about. By passing functions, my longWayAroundTheBarn doesn't care if I create new functions and pass it to it. Note that because of weak typing, it doesn't even need to care about the parameters it is passing. Maybe you want to implement something like

 function businessDaysBetween(d1,d2)
 {
     // implementation left as a reader exercise
 };

它可以正常工作:

longWayAroundTheBarn(new Date(2014,1,15), new Date(2014,1,22),businessDaysBetween)

回到你提出的具体案例, req res 不是'局部变量',如一个答案所示 - 它们被称为参数或参数。你没有把任何东西传递给他们。它们由调用函数传递给您。如果你愿意,你实际上可以称它们为 fred barney ,尽管这可能是一个糟糕的主意。重点是它们将被调用填充请求和响应对象。

Returning to the specific case you raised, req and res are not 'local variables' as one answer indicates - they are called parameters or arguments. You aren't passing anything into them. They are being passed to you by the calling function. You could actually call them fred and barney if you wanted, although it would be a terrible idea. The main point is that they will be called populated with request and response objects.

你实际上甚至不需要在函数签名中包含参数,你可以只是有一个回调如下,并通过读取arguments数组使用传递给你的函数的第二个参数(注意,它实际上不是一个数组,但在许多方面表现相似)。这将是一个可怕的,可怕的想法,但再次,试图说明这一点。

You actually don't even have to have the parameters in your function signature, you could just have a callback as below, and make use of the second parameter passed to your function by reading the arguments array (Note, it's not actually an array but behaves similarly in many respects). This would be a terrible, terrible idea, but again, trying to illustrate the point.

      var http = require('http');
      http.createServer(function () {
             arguments[1].writeHead(200, {'Content-Type': 'text/plain'});
             arguments[1].end('Hello World\n');
      }).listen(1337, 'myhost');

这篇关于Node JS匿名函数和回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆