更好地理解 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 中,如果我确实返回了 new 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();

如果您想在回调中调整 this 的值,也可以使用 call 方法.

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

callback.call( newValueForThis);

在函数 this 中,newValueForThis 是什么.

Inside the function this would be whatever newValueForThis is.