Getting a better understanding of callback functio

2018-12-31 21:08发布

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.
        });
    }
};

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.

8条回答
裙下三千臣
2楼-- · 2018-12-31 21:38

You can just say

callback();

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

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 21:40

You should check if the callback exists, and is an executable function:

if (callback && typeof(callback) === "function") {
    // execute the callback, passing parameters as necessary
    callback();
}

A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as node.js for all async functions (nodejs usually passes error and data to the callback). Looking into their source code would help!

查看更多
有味是清欢
4楼-- · 2018-12-31 21:41

There are 3 main possibilities to execute a function:

var callback = function(x, y) {
    // "this" may be different depending how you call the function
    alert(this);
};
  1. callback(argument_1, argument_2);
  2. callback.call(some_object, argument_1, argument_2);
  3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

  1. You have the arguments stored in an Array or as distinct variables.
  2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply

查看更多
骚的不知所云
5楼-- · 2018-12-31 21:41

the proper implementation would be:

if( callback ) callback();

this makes the callback parameter optional..

查看更多
只若初见
6楼-- · 2018-12-31 21:49

You can use:

if (callback && typeof(callback) === "function") {
    callback();
}

the below example is little more comprehensive:

function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
var sandwich = {toppings: [param1, param2]},
    madeCorrectly = (typeof(param1) === "string" && typeof(param2) === "string") ? true : false;
if (callback && typeof(callback) === "function") {  
    callback.apply(sandwich, [madeCorrectly]);  
  }  
}  

mySandwich('ham', 'cheese', function(correct) {
if(correct) {
    alert("Finished eating my " + this.toppings[0] + " and " + this.toppings[1] + " sandwich.");
} else {
    alert("Gross!  Why would I eat a " + this.toppings[0] + " and " + this.toppings[1] + " sandwich?");
  }
});
查看更多
春风洒进眼中
7楼-- · 2018-12-31 21:51
function checkCallback(cb)
{
    if(cb || cb!='')
    {
        if(typeof window[cb] === 'undefined') alert('Callback function not found.');
        else window[cb].call(this,Arg1, Arg2);
    }
}
查看更多
登录 后发表回答