更好地理解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 是。