简体   繁体   中英

How to call a function from a function argument in JavaScript?

So I read the tutorial from some web, and they did something like this.

function populateDB(tx) {
     tx.executeSql('DROP TABLE IF EXISTS DEMO');
     tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

function successCB() {
    alert("success!");
}

var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);

In the last line, they called the method transaction from object db, and there are 3 functions in the argument field, but isn't the functions populateDB, errorCB both need an argument as well? Where is that argument being called?

The database runtime will call those functions when it wants to, and it will pass in the parameters. In the "db.transaction" function call, you're passing in references to the functions. At that point, function parameters are not needed because you're just identifying which functions to call.

Those are callbacks, which means that the transaction method will call one or the other CB functions dependent upon success or failure.

That method might work like this:

db.transaction = function(populateDB, errorCB, successCB) {
    // Try to do the requested action
    var tx = performTransaction(populateDB);

    // If the action failed, call the error callback, 
    // otherwise call the success callback
    if (tx==false) {
        var err = new TransactionError();
        return errorCB(err);
    } else {
        return successCB(tx);
    }
}

Those functions receive argument automatically based on the way the callback is designed. You pass in a reference to your function and when the callback uses that reference it populates the parameters based on how the whole mechanism is built. Basically the transaction Object knows to call methods for which you have supplied the reference and pass in whatever it intends to pass in. It's up to you to make sure to collect it (as you're doing).

The only reason this is a tad confusing is because you haven't cracked open the transaction Function. If you did, you'd see it calling those functions and passing in the values you are later collecting).

javascript有几种在函数内部获取/设置数据的方法,请参见:方法-callapplyarguments var

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM