更好地理解JavaScript中的回调函数 [英] Getting a better understanding of callback functions in JavaScript

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

问题描述

我理解将一个函数传递给另一个函数作为一个回调,并让它执行,但我不知道最好的实现。我正在寻找一个非常基本的例子,像这样:

I understand passing in a function to another function as a callback and having it execute, but I'm not understanding the best implementation to do that. I'm looking for a very basic example, like this:

var myCallBackExample = {
    myFirstFunction : function( param1, param2, callback ) {
        // Do something with param1 and param2.
        if ( arguments.length == 3 ) {
            // Execute callback function.
            // What is the "best" way to do this?
        }
    },
    mySecondFunction : function() {
        myFirstFunction( false, true, function() {
            // When this anonymous function is called, execute it.
        });
    }
};

在myFirstFunction中,如果我返回新的callback(),它会工作并执行匿名函数,

In myFirstFunction, if I do return new callback(), then it works and executes the anonymous function, but that doesn't seem like the correct approach to me.

推荐答案

您可以说

callback();

或者,您可以使用调用方法if您要在回调中调整 this 的值。

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

code> newValueForThis 是。

这篇关于更好地理解JavaScript中的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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