AniMir
AniMir

Reputation: 160

What are those Javascript functions parameters and how does it work ? (native parameters)

In this tiny bit of (pure) js code, for example :

document.getElementById("example").addEventListener('click', function(event) {
    event.preventDefault();
}

What exactly is this "event" parameter ? I could also call it "myGoat", right ? Where/when is it defined that this parameter refers to the actual event ?

Another jQuery example :

request = $.ajax({
        url: "cre_devis.php",
        type: "post",
        data: someData
});
request.done(function (response, textStatus, jQueryXMLHttpRequest){
    document.getElementById("serverAnswer").innerHTML = response;
});

How are response, textStatus and jQueryXMLHttpRequest defined ? I suppose it is related to the .done method ?

Upvotes: 0

Views: 69

Answers (1)

Abhas Tandon
Abhas Tandon

Reputation: 1889

Those are callback functions and they receive the parameter from the code which is calling it which in this case happens on some event such as an event.

Every function in JavaScript is a Function object. You can pass it as a parameter to some other function like any other object. Example:

function bar(value, callback) {
  callback(value);
}

bar('actual value', function(value) {
  console.log(value);
});

You can read about callback functions at: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

Upvotes: 3

Related Questions