JavaScript function call

To call, for example, a function called makeRequest, I found out that you need to do makeRequest(); . If you do only makeRequest; This is a link to a function (I thought). However, looking at this code (which worked when I tested it), it calls makeRequest; in the window. Download without partners.

Can someone explain?

 window.onload = makeRequest; var xhr = false; function makeRequest() { if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { if (window.ActiveXObject) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } if (xhr) { xhr.onreadystatechange = showContents; xhr.open("GET", "colors.xml", true); xhr.send(null); } else { document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest"; } } function showContents() { if (xhr.readyState == 4) { if (xhr.status == 200) { var outMsg = xhr.responseText; } else { var outMsg = "There was a problem with the request " + xhr.status; } document.getElementById("updateArea").innerHTML = outMsg; } } 
+4
source share
2 answers

In this line:

 window.onload = makeRequest; 

the makeRequest function makeRequest not called . You only assign a function pointer to the onload . When the DOM loads, the browser automatically raises this event, and only at that moment the called function is called (which can happen much later, but will leave you with the impression that the function is called immediately).

+6
source

This is the link used on the right side of the expression. i.e

 var x = myfunction; 

would set x as a "pointer" to my function.

 var x = myfunction(); 

will store the return-by-myfunction value in x.

+3
source

Source: https://habr.com/ru/post/1347203/


All Articles