简体   繁体   English

在JavaScript中传递匿名函数中的参数

[英]Passing arguments in anonymous functions in JavaScript

Sometimes I see JavaScript that is written with an argument provided that already has a set value or is an object with methods. 有时我看到用参数编写的JavaScript,只要已经有一个设置值或者是一个带方法的对象。 Take this jQuery example for instance: 以这个jQuery示例为例:

$(".selector").children().each(function(i) {
    console.log(i);
});

When logging i , you would get the value of whatever i is in that iteration when looking at the selectors children in the jQuery each method. 当登录i ,你会得到什么价值i看孩子选择在jQuery的时候是在迭代each方法。

Take this Node.js example: 拿这个Node.js例子:

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

You can see here that request and response are being passed and they contain their own methods that can be acted on. 您可以在此处看到正在传递requestresponse ,并且它们包含可以对其执行操作的自己的方法。

To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them. 对我来说,这看起来像是将一个函数传递给createServer函数,其中两个参数已经附加了方法。

My question is a multipart one: 我的问题是多部分:

  1. Where do these arguments come from? 这些论点来自哪里?
  2. If these are just anon functions, how do they receive arguments that can be acted on like other functions? 如果这些只是一个函数,它们如何接收可以像其他函数一样执行的参数?
  3. How do I create functions that can take my own arguments like this?? 如何创建可以采用我自己的参数的函数?
  4. Does this use the power of closures?? 这是否使用了封闭的力量?

To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them. 对我来说,这看起来像是将一个函数传递给createServer函数,其中两个参数已经附加了方法。

No. They were passing a function to createServer that takes two arguments. 不,他们正在将一个函数传递给带有两个参数的createServer Those functions will later be called with whatever argument the caller puts in. eg: 稍后将使用调用者输入的任何参数调用这些函数。例如:

function caller(otherFunction) {
     otherFunction(2);
 }
caller(function(x) {
    console.log(x); 
});

Will print 2. 将打印2。

More advanced, if this isn't what you want you can use the bind method belong to all functions, which will create a new function with specified arguments already bound. 更高级,如果这不是您想要的,您可以使用属于所有函数的bind方法,这将创建一个已绑定指定参数的新函数。 eg: 例如:

caller(function(x) {
    console.log(x);
}.bind(null, 3);
});

Will now print 3, and the argument 2 passed to the anonymous function will become an unused and unnamed argument. 现在将打印3,并且传递给匿名函数的参数2将成为未使用且未命名的参数。

Anyway, that is a dense example; 无论如何,这是一个密集的例子; please check the linked documentation for bind to understand how binding works better. 请检查bind的链接文档,以了解bind如何更好地工作。

Let's take a look at $.each for the example: 我们来看看$.each示例:

each: function (obj, callback, args) {
    var value,
    i = 0,
        length = obj.length,
        isArray = isArraylike(obj);

    if (args) {
        if (isArray) {
            for (; i < length; i++) {
                value = callback.apply(obj[i], args);

                if (value === false) {
                    break;
                }
            }
        } else {
            for (i in obj) {
                value = callback.apply(obj[i], args);

                if (value === false) {
                    break;
                }
            }
        }

        // A special, fast, case for the most common use of each
    } else {
        if (isArray) {
            for (; i < length; i++) {
                value = callback.call(obj[i], i, obj[i]);

                if (value === false) {
                    break;
                }
            }
        } else {
            for (i in obj) {
                value = callback.call(obj[i], i, obj[i]);

                if (value === false) {
                    break;
                }
            }
        }
    }

    return obj;
}

This gets called from 这是从中调用的

$(".selector").children().each(function(i) {
    console.log(i);
});

like: 喜欢:

return $.each.call(this, callback /* this is your function */, args /* which is an additional thing people rarely use*/ )

This is the line (in the first block) you want to look at 这是您想要查看的行(在第一个块中)

callback.call(obj[i], i, obj[i]);

It's calling the callback, and passing the object as the context – this is why you can use this in the loop. 它调用回调,并将对象作为上下文传递 - 这就是为什么你可以在循环中使用this Then the iteration i and then the same object as the context are both sent as arguments to the callback. 然后迭代i和然后与上下文相同的对象都作为参数发送到回调。 It's a little bit like magic; 这有点像魔术; until you look at the source code. 直到你看源代码。

Here's a example of passing parameters into anonymous function 这是将参数传递给匿名函数的示例

    var a = 'hello';

    // Crockford
    (function(a){alert(a)}(a));

    // Others
    (function(a){alert(a)})(a);

It uses closure, since it's an anonymous function (it actually all depends how you wrote it) 它使用闭包,因为它是一个匿名函数(它实际上取决于你如何写它)

Yes, you are passing functions as arguments. 是的,您将函数作为参数传递。 The functions that you pass will of course have their own arguments. 您传递的函数当然会有自己的参数。

And, these arguments can be anything including objects which may have their own methods, etc. 而且,这些参数可以是任何包括可能有自己方法的对象等。

http.createServer will accept a function and it will know how may arguments that function has. http.createServer将接受一个函数,它将知道函数的参数如何。 One way to to do this is to check the arguments property of the passed in function. 一种方法是检查传入函数的arguments属性。 Or the api developer may have used the actual elements. 或者api开发人员可能已经使用了实际元素。

The writer of this function will know what is expected as arguments and will document it in the api documentation . 这个函数的作者将知道什么是期望的参数,并将在api documentation记录它。

If you looked at the code for createServer, it'd look something like this: 如果您查看createServer的代码,它看起来像这样:

function createServer (handleRequestAndResponseFunction) {
    handleRequestAndResponseFunction(actualRequest, actualReponse);
}

ok, no it wouldn't, but it's a simple example. 好吧,不,不会,但这是一个简单的例子。 createServer takes a function that accepts two arguments. createServer需要一个function接受两个参数。

In more realistic terms, when you pass in that function of two arguments, it does whatever middleware processing and stuff that it needs to, and then calls that function, passing its own request and response variables. 用更现实的术语来说,当你传入两个参数的函数时,它会做任何中间件处理和它需要的东西,然后调用该函数,传递它自己的请求和响应变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM