Learn about javascript call (), apply (), bind () and callback. If you are interested, refer
I. call (), apply (), bind () method
In JavaScript, call or apply is used to call a method instead of another object, and the object context of a function is changed from the initial context to the new object specified by thisObj. Simply put, the context of function execution is changed, which is the most basic usage. The basic difference between the two methods is that parameter passing is different.
Call (obj, arg1, arg2, arg3); call the first parameter to pass the object, which can be null. The parameters are separated by commas (,). The parameters can be of any type.
Apply (obj, [arg1, arg2, arg3]); apply the first parameter to pass the object. The parameter can be an array or arguments object.
1. Syntax
Let's take a look at the call explanation in the JS manual:
Call Method
Call a method of one object to replace the current object with another object.
Call ([thisObj [, arg1 [, arg2 [, [,. argN])
Parameters
ThisObj is optional. Will be used as the object of the current object.
Arg1, arg2, and arg are optional. The method parameter sequence will be passed.
Description
The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj.
If the thisObj parameter is not provided, the Global object is used as thisObj.
The white point is actually to change the internal pointer of the object, that is, to change the content that this points to of the object. This is sometimes useful in Object-Oriented js programming.
2. Usage
Because function is an object, each function contains two non-inherited methods: apply () and call (). The purpose of these two methods is to call a function in a specific scope, which is actually equal to setting the value of this object in the function body. First, the apply () method receives two parameters: one is the scope in which the function is run, and the other is the parameter array. The second parameter can be an Array instance or an arguments object. For example:
Function sum (num1, num2) {return num1 + num2;} function callSum1 (num1, num2) {return sum. apply (this, arguments); // input arguments object} function callSum2 (num1, num2) {return sum. apply (this, [num1, num2]); // input array} alert (callSum1 (10, 10); // 20 alert (callSum2 (10, 10); // 20
In the above example, callSum1 () passed this as the value of this when executing the sum () function (because it is called in the global scope, it is passed in the window object) and arguments object. CallSum2 also calls the sum () function, but it imports this and a parameter array. Both functions run normally and return correct results.
In strict mode, if a function is called without an environment object specified, the value of this is not converted to window. Unless you explicitly add a function to an object or call apply () or call (), the value of this will be undefined.
3. Differences
The call () method and the apply () method have the same effect. The difference is that the method of receiving parameters is different. For the call () method, the first parameter is that the value of this has not changed, and all other parameters are directly transferred to the function. In other words, when using the call () method, the parameters passed to the function must be listed one by one, as shown in the following example.
function sum(num1, num2){ return num1 + num2;}function callSum(num1, num2){ return sum.call(this, num1, num2);}alert(callSum(10,10)); //20
When the call () method is used, callSum () must explicitly input each parameter. The result is no different from apply. The use of apply () or call () depends entirely on the method you use to pass parameters to the function. If you want to directly pass in the arguments object or include an array that is first received by the function, it is more convenient to use apply (). Otherwise, call () may be more suitable. (It doesn't matter which method to use without passing parameters to the function ).
4. Expand the function running Scope
In fact, passing parameters is not really useful for both apply () and call (); what they really do is the ability to expand functions.
The running scope. The following is an example.
window.color = "red";var o = { color: "blue" };function sayColor(){ alert(this.color);}sayColor(); //redsayColor.call(this); //redsayColor.call(window); //redsayColor.call(o); //blue
This example is modified based on the preceding example of this object. This time, sayColor () is also defined as a global function, and when it is called in a global scope, it does display "red" -- because of this. the value of color is converted to window. evaluate the color. SayColor. call (this) and sayColor. call (window) are two methods to explicitly call a function in the global scope, and the result will certainly display "red ". However, when sayColor. call (o) is run, the execution environment of the function is different, because the this object in the function body points to o, and the result is displayed as "blue ". The biggest benefit of using call () (or apply () to expand the scope is that the object does not need to have any coupling relationship with the method.
In the first version of the previous example, we first put the sayColor () function into the object o, and then call it through o. In the example rewritten here, there is no need for the previous redundant steps.
5. bind () method
Finally, for the bind () function, whether it is call () or apply (), it immediately calls the corresponding function, and bind () does not, bind () generates a new function. The parameters of the bind () function are the same as those of the call () function. The first parameter is the value bound to this function, and the variable parameters passed to the function are accepted later. After the new function generated by bind () is returned, when do you want to call it,
window.color = "red";var o = { color: "blue" };function sayColor(){ alert(this.color);}var objectSayColor = sayColor.bind(o);objectSayColor(); //blue
Here, sayColor () calls bind () and passes in object o to create the objectSayColor () function. The this value of the object-SayColor () function is equal to o, so even if you call this function in a global scope, you will see "blue ".
Browsers that support the bind () method include IE9 +, Firefox 4 +, Safari 5.1 +, Opera 12 +, and Chrome.
Ii. Inheritance and callback of call () and apply ()
Class inheritance
Let's take a look at this example:
Function Person (name, age) {this. name = name; this. age = age; this. alertName = function () {alert (this. name);} this. alertAge = function () {alert (this. age) ;}} function webDever (name, age, sex) {Person. call (this, name, age); this. sex = sex; this. alertSex = function () {alert (this. sex) ;}} var test = new webDever ("Stupid dock", 28, "male"); test. alertName (); // test. alertAge (); // 28test. alertSex (); // male
In this way, the webDever class inherits the Person class, Person. call (this, name, age) means to use the Person Constructor (also a function) to execute in this object, so webDever has all the attributes and methods of Person, the test object can directly call the Person method and attributes.
Used for callback
Call and apply are also very useful in the number of callback rows. In many cases, we need to change the execution context of the callback function during development, such as ajax or timing. In general, ajax is global, that is, under the window object. Let's look at this example:
Function Album (id, title, owner_id) {this. id = id; this. name = title; this. owner_id = owner_id;}; Album. prototype. get_owner = function (callback) {var self = this; $. get ('/owners/' + this. owner_id, function (data) {callback & callback. call (self, data. name) ;};}; var album = new Album (1, 'LIFE', 2); album. get_owner (function (owner) {alert (The album '+ this. name + 'belongs to '+ owner );});
Here
album.get_owner(function (owner) { alert(‘The album' + this.name + ‘ belongs to ‘ + owner);});
This. name in can directly obtain the name attribute in the album object.
Iii. Callback Functions
When talking about callback functions, many people know what they mean, but they still have some knowledge. I am confused about how to use it. I have not explained in detail what is going on the Internet. Next I will just talk about my personal understanding. Do not spray it.
Definition
What is callback?
Check the Callback _ (computer_programming) entries of the Wiki:
In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.
In JavaScript, the callback function is defined as: function A is passed to another function B as A parameter (function reference), and function B executes function. Function A is called A callback function. If there is no name (function expression), it is called an anonymous callback function.
For example:
What do you do if you go to the dormitory next door and find someone else is absent?
Method 1: Go to the next bedroom every few minutes.
Method 2. Please contact the person in the same dormitory and call you when he returns.
The former is polling, and the latter is callback.
Then you said, can I wait for my classmates to return directly in the dormitory next door?
Yes, but you can save time to do other things. Now you have to waste your time waiting.
Turns the original non-blocking asynchronous call into a blocking synchronous call.
JavaScript callback is used in asynchronous call scenarios. The callback performance is better than that of polling.
Therefore, callback is not necessarily used for Asynchronization. callback is often used in synchronous (blocking) scenarios. For example, a callback function is required to be executed after certain operations.
An example of using callback in synchronization (blocking) is to execute func2 after the func1 code is executed.
var func1=function(callback){ //do something. (callback && typeof(callback) === "function") && callback();}func1(func2); var func2=function(){}
Example of asynchronous callback:
$(document).ready(callback);$.ajax({ url: "test.html", context: document.body}).done(function() { $(this).addClass("done");}).fail(function() { alert("error");}).always(function() { alert("complete"); });
When will the callback be executed?
The callback function is generally last executed in a synchronous situation, but may not be executed in an asynchronous situation because the event is not triggered or the conditions are not met. In addition, it is best to ensure that the callback exists and must be a function reference or function expression:
(Callback & typeof (callback) === "function") & callback ();
Let's look at a rough definition: "function a has a parameter, which is function B. function B is executed after function a is executed. This process is called callback .", This sentence means that function B passes in function a as a parameter and executes it. The sequence is to first execute a, then execute parameter B, and B is the so-called callback function. Let's take a look at the example below.
Function a (callback) {alert ('A'); callback. call (this); // or callback (), callback. apply (this), depending on your preferences} function B () {alert ('B');} // call a (B );
The result is 'A' first and then 'B '. In this case, someone may ask, "What does this code mean? It doesn't seem to have much effect !"
Yes, in fact, I don't think it's interesting to write it like this. "If you call a function, you just need to call it directly in the function ". I am only writing a small example for you to make a preliminary understanding. In most scenarios, we need to pass parameters. To include the following parameters:
Function c (callback) {alert ('C'); callback. call (this, 'D');} // call c (function (e) {alert (e );});
This call seems familiar to me. Here, the e parameter is assigned as 'D'. We simply assign a value to the character escape, but it can also be assigned as an object. Is there an e parameter in Jquery?
Usage of callback Functions
- Resource loading: callback is executed after js files are dynamically loaded, callback is executed after iframe is loaded, callback for ajax operations, callback for image loading completion, AJAX, and so on.
- DOM events and Node. js events are based on callback mechanisms (Node. js callbacks may cause multi-layer callback nesting issues ).
- The latency of setTimeout is 0, which is often used. The settimeout function is actually a callback.
- Chain call:During a chain call, the setter method (or a method without a return value) can easily implement a chain call, while the getter Method) it is relatively difficult to implement chained call, because you need the iterator to return the data you need instead of the this pointer. If you want to implement the chained method, you can use the callback function to implement it.
- SetTimeout and setInterval functions call to obtain their return values. Because both functions are asynchronous, that is, their call sequence and the main process of the program are relatively independent, there is no way to wait for their return values in the subject, when they are opened, the program will not stop and wait. Otherwise, the meaning of setTimeout and setInterval will be lost. Therefore, it is meaningless to use return, and only callback can be used. Callback notifies the proxy function of the result of timer execution for timely processing.
When the function implementation process is very long, do you choose to wait for the function to complete processing, or use the callback function for asynchronous processing? In this case, using callback functions becomes crucial, such as AJAX requests. If the callback function is used for processing, the code can continue with other tasks without being empty. In actual development, asynchronous calls are often used in javascript, and it is even strongly recommended here!
The following is a more comprehensive example of loading XML files using AJAX, and the call () function is used to call the callback function in the context of the request object (requested object.
Function fn (url, callback) {var httpRequest; // create XHR httpRequest = window. XMLHttpRequest? New XMLHttpRequest (): window. ActiveXObject? New ActiveXObject ("Microsoft. XMLHTTP "): undefined; // perform functional check httpRequest for IE. onreadystatechange = function () {if (httpRequest. readystate === 4 & httpRequest. status = 200) {// status callback. call (httpRequest. responseXML) ;}}; httpRequest. open ("GET", url); httpRequest. send ();} fn ("text. xml ", function () {// call the function console. log (this); // output after this statement}); console. log ("this will run before the above callback. "); // This statement is output first
Asynchronous request processing means that when we start the request, we will tell them to call our function when they are completed. In actual situations, the onreadystatechange event handler must consider request failure. Here we assume that the xml file exists and can be loaded successfully by the browser. In this example, the asynchronous function is assigned to the onreadystatechange event, so it is not executed immediately.
Finally, the second console. log statement is executed first, because the callback function is not executed until the request is complete.
The above is all the content of this article, hoping to help you learn.
For details, see: JavaScript callback function