Javascript函数作为另一个函数的参数? [英] Javascript function as a parameter to another function?

查看:77
本文介绍了Javascript函数作为另一个函数的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天我学习了很多javascript,其中一个我不太了解的事情是将函数作为参数传递给其他函数。我得到了做这些事情的概念,但我自己无法想出任何理想的情况。

I'm learning lots of javascript these days, and one of the things I'm not quite understanding is passing functions as parameters to other functions. I get the concept of doing such things, but I myself can't come up with any situations where this would be ideal.

我的问题是:

您希望什么时候让您的javascript函数将另一个函数作为参数?为什么不直接为该函数的返回值赋值,并将该变量传递给函数,如下所示:

When do you want to have your javascript functions take another function as a parameter? Why not just assign a variable to that function's return value and pass that variable to the function like so:

// Why not do this
var foo = doStuff(params);
callerFunction(foo);

//instead of this
callerFunction(doStuff);

我很困惑为什么我会选择做第二个例子中的事情。

I'm confused as to why I would ever choose to do things as in my second example.

你为什么要这样做?有什么用例?

Why would you do this? What are some use cases?

谢谢!!

推荐答案

那里有几种用例:

假设您有许多不同的代码。在每一段代码之前和之后,你想要做其他的事情(例如:log或try / catch异常)。

Lets say you have a bunch of different bits of code. Before and after every bit of code, you want to do something else (eg: log, or try/catch exceptions).

你可以写一个Wrapper函数处理这个(事情。 EG:

You can write a "Wrapper" function to handle this. EG:

function putYourHeadInTheSand(otherFunc) {
    try{
         otherFunc();
    } catch(e) { } // ignore the error
}

....

putYourHeadInTheSand(function(){
    // do something here
});
putYourHeadInTheSand(function(){
    // do something else
});



2。回调。



让我们假设你以某种方式加载一些数据。而不是锁定系统等待它加载,你可以在后台加载它,并在结果到达时对结果做一些事情。

2. Callbacks.

Lets say you load some data somehow. Rather than locking up the system waiting for it to load, you can load it in the background, and do something with the result when it arrives.

现在你怎么知道什么时候到?你可以使用像信号或互斥的东西,这很难写和丑,或者你可以只做一个回调函数。您可以将此回调传递给Loader函数,该函数可以在完成后调用它。

Now how would you know when it arrives? You could use something like a signal or a mutex, which is hard to write and ugly, or you could just make a callback function. You can pass this callback to the Loader function, which can call it when it's done.

每次执行 XmlHttpRequest ,这正是发生的事情。这是一个例子。

Every time you do an XmlHttpRequest, this is pretty much what's happening. Here's an example.

function loadStuff(callback) {
    // Go off and make an XHR or a web worker or somehow generate some data
    var data = ...;
    callback(data);
}

loadStuff(function(data){
    alert('Now we have the data');
});



3。生成器/迭代器



这类似于回调,但不是只调用一次回调,而是可以多次调用它。想象一下,你的加载数据函数不只是加载一位数据,也许加载200。

3. Generators/Iterators

This is similar to callbacks, but instead of only calling the callback once, you might call it multiple times. Imagine your load data function doesn't just load one bit of data, maybe it loads 200.

这最终与for / foreach循环非常相似,除了它的异步。 (你不等待数据,当它准备好时它就会调用你。)

This ends up being very similar to a for/foreach loop, except it's asynchronous. (You don't wait for the data, it calls you when it's ready).

function forEachData(callback) {
    // generate some data in the background with an XHR or web worker
    callback(data1);
    // generate some more data in the background with an XHR or web worker
    callback(data2);
    //... etc
}

forEachData(function(data){
    alert('Now we have the data'); // this will happen 2 times with different data each time
});



4。延迟加载



假设您的函数对某些文本执行了某些操作。但它只需要文本中的一次可能是5次,并且加载文本可能非常昂贵。

4. Lazy loading

Lets say your function does something with some text. BUT it only needs the text maybe one time out of 5, and the text might be very expensive to load.

所以代码看起来像这样

var text = "dsakjlfdsafds"; // imagine we had to calculate lots of expensive things to get this.
var result = processingFunction(text);

处理功能实际上只需要20%的时间来处理文本!我们浪费了所有这些额外的时间加载它。

The processing function only actually needs the text 20% of the time! We wasted all that effort loading it those extra times.

您可以传递一个生成文本的函数,而不是传递文本,如下所示:

Instead of passing the text, you can pass a function which generates the text, like this:

var textLoader = function(){ return "dsakjlfdsafds"; }// imagine we had to calculate lots of expensive things to get this.
var result = processingFunction(textLoader);

您必须更改 processingFunction 期待另一个功能而不是文本,但这确实很小。现在发生的是 processingFunction 只会在需要它的20%的时间内调用 textLoader 。其他80%的时间,它不会调用该功能,你也不会浪费所有的努力。

You'd have to change your processingFunction to expect another function rather than the text, but that's really minor. What happens now is that the processingFunction will only call the textLoader the 20% of the time that it needs it. The other 80% of the time, it won't call the function, and you won't waste all that effort.

如果您发生了延迟加载,那么 textLoader 函数可以将结果文本私下存储在一旦得到它就变量。第二次有人调用 textLoader 时,它可以返回该变量并避免昂贵的计算工作。

If you've got lazy loading happening, then the textLoader function can privately store the result text in a variable once it gets it. The second time someone calls the textLoader, it can just return that variable and avoid the expensive calculation work.

调用 textLoader 的代码不知道或不关心数据是否被缓存,它透明地更快。

The code that calls textLoader doesn't know or care that the data is cached, it's transparently just faster.

那里通过传递函数可以做很多更高级的事情,这只是表面上看,但希望它指出你正确的方向: - )

There are plenty more advanced things you can do by passing around functions, this is just scratching the surface, but hopefully it points you in the right direction :-)

这篇关于Javascript函数作为另一个函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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