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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18195750/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:02:45  来源:igfitidea点击:

Passing arguments in anonymous functions in JavaScript

javascript

提问by Sethen

Sometimes I see JavaScript that is written with an argument provided that already has a set value or is an object with methods. Take this jQuery example for instance:

有时我会看到 JavaScript 是用一个参数编写的,该参数已经有一个设置值或者是一个带有方法的对象。以这个 jQuery 示例为例:

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

When logging i, you would get the value of whatever iis in that iteration when looking at the selectors children in the jQuery eachmethod.

在记录时ii当查看 jQueryeach方法中的选择器子项时,您将获得该迭代中任何内容的值。

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 requestand responseare 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 createServerfunction 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??
  1. 这些论据从何而来?
  2. 如果这些只是匿名函数,它们如何接收可以像其他函数一样作用的参数?
  3. 如何创建可以像这样使用我自己的参数的函数?
  4. 这是否使用了闭包的力量?

采纳答案by djechlin

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 createServerthat takes two arguments. Those functions will later be called with whatever argument the caller puts in. e.g.:

不,他们传递了一个createServer需要两个参数的函数。稍后将使用调用者输入的任何参数调用这些函数。例如:

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

Will print 2.

将打印 2。

More advanced, if this isn'twhat you want you can use the bindmethod belong to all functions, which will create a new function with specified arguments already bound. e.g.:

更高级的是,如果这不是您想要的,您可以使用属于所有函数的bind方法,这将创建一个具有已绑定的指定参数的新函数。例如:

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 bindto understand how binding works better.

无论如何,这是一个密集的例子;请查看链接的文档bind以了解绑定如何更好地工作。

回答by kalley

Let's take a look at $.eachfor 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 thisin the loop. Then the iteration iand then the same object as the context are both sent as arguments to the callback. It's a little bit like magic; until you look at the source code.

它调用回调,并将对象作为上下文传递——这就是您可以this在循环中使用的原因。然后迭代i和与上下文相同的对象都作为参数发送到回调。这有点像魔术;直到你查看源代码。

回答by Alan Dong

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)

它使用闭包,因为它是一个匿名函数(这实际上完全取决于您如何编写它)

回答by Phillip Schmidt

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 functionthat 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.

在更现实的情况下,当您传入该函数的两个参数时,它会执行所需的任何中间件处理和内容,然后调用该函数,传递其自己的请求和响应变量。

回答by Smurfette

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.createServerwill accept a function and it will know how may arguments that function has. One way to to do this is to check the argumentsproperty of the passed in function. Or the api developer may have used the actual elements.

http.createServer将接受一个函数,它会知道该函数有多少参数。一种方法是检查arguments传入函数的属性。或者 api 开发人员可能使用了实际元素。

The writer of this function will know what is expected as arguments and will document it in the api documentation.

此函数的作者将知道期望作为参数的内容并将其记录在api documentation.