call()
and apply()
functions or short pieces of code that demonstrate their use, and now, having stuffed cones in search of truth, I I decided to write an introduction to the callback function myself.Function
class created by the Function
constructor. The Function
object contains a string with the JS code of this function. If you have moved from C or Java, this may seem strange (how can the code be a string ?!), but generally speaking, in Javascript this is very often. The distinction between code and data is sometimes blurred. // , Function var func_multiply = new Function("arg1", "arg2", "return arg1 * arg2;"); func_multiply(5, 10); // => 50
// callback function some_function(arg1, arg2, callback) { // , arg1 arg2 var my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2); // callback, callback(my_number); } // some_function(5, 15, function (num) { // callback- console.log("callback called! " + num); });
return
expression (ideally, the only return
expression at the end of the function is one entry point and one exit point). It makes sense. Functions are essentially routes between input and output.call()
function to call a callback function in the context of the requested object (this means that when we specify this
inside the callback function, it will refer to the requested an object): function some_function2(url, callback) { var httpRequest; // XMLHttpRequest- if (window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer' httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } httpRequest.onreadystatechange = function () { // // if (httpRequest.readyState === 4 && httpRequest.status === 200) { callback.call(httpRequest.responseXML); // } }; httpRequest.open('GET', url); httpRequest.send(); } // some_function2("text.xml", function () { console.log(this); }); console.log(" ");
call()
function to do this. This is another way to call a callback function. The method we used before - a simple start of a function here would work well, but I thought it worth exploring the use of the call()
function. Alternatively, you can use the apply()
function (a discussion of the difference between it and call()
beyond the scope of this article, I will only say that this affects the way the function arguments are passed).call()
great that we ourselves set the context in which the function is executed. This means that when we use the this
inside our callback function, it refers to the fact that we pass the first argument to call()
. In this example, when we referenced this inside our anonymous function, we referenced the responseXML received as the result of an AJAX request.Source: https://habr.com/ru/post/151716/
All Articles