Follow me to learn about JavaScript call (), apply (), bind () and callback _javascript tips

Source: Internet
Author: User
Tags setinterval

One, call (), apply (), bind () method

In JavaScript, a method is invoked to replace another object by calling or apply, changing the object context of a function from the initial context to the new object specified by Thisobj. The simple thing is to change the context in which the function executes, which is the most basic usage. The basic difference of two methods is that the parameters are different.

Call (OBJ,ARG1,ARG2,ARG3); Call the first parameter to pass the object, can be null. Parameters are passed as commas, and arguments can be of any type.
Apply (OBJ,[ARG1,ARG2,ARG3]); Apply the first argument to the object, which can be either an array or a arguments object.
1. Grammar
First look at the JS manual in the explanation of call:

Call method
invokes one of the object's methods to replace the current object with another object.

Call ([thisobj[,arg1[, arg2[, [,. argn]]]]
parameters

Thisobj can be selected. The object that will be used as the current object.
Arg1, arg2, arg available option. A sequence of method parameters is passed.
description
The call method can be used to invoke 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 supplied, the Global object is used as a thisobj.
To be clear is to change the inner pointer of an object, that is, to change the content that this object is pointing to. This is sometimes useful in the object-oriented JS programming process.

2. Usage

Because functions are also objects, each function contains two methods that are not inherited: Apply () and call (). The purpose of both methods is to call a function in a particular scope, which is actually equal to the value of the 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 an array of arguments. Where the second argument can be an instance of an array, or it can be a arguments object. For example:

function sum (NUM1, num2) {return
 num1 + num2;
}
function CallSum1 (NUM1, num2) {return
 sum.apply (this, arguments);//Incoming arguments object
}
function callSum2 ( NUM1, num2) {return
 sum.apply (this, [Num1, num2]);//incoming array
}
alert (CALLSUM1 (10,10));//20
alert ( CallSum2 (10,10)); 20

In the example above, CALLSUM1 () passed the this as this value when executing the sum () function (because it was called in the global scope, so the window object was passed in) and the arguments object. CALLSUM2 also called the sum () function, but it passed in this and an array of arguments. Both functions execute correctly and return the correct result.

In strict mode, when you do not specify an environment object and call a function, the this value does not transition to window. Unless you explicitly add a function to an object or invoke apply () or call (), the This value will be undefined

3, different points

The call () method works the same as the Apply () method, which differs only in the way that the parameters are received. For the call () method, the first argument is that the this value does not change, and the rest of the parameters are passed directly to the function. In other words, when using the call () method, the arguments passed to the function must be enumerated individually, 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

With the call () method, Callsum () must explicitly pass in each parameter. The results are no different from using apply (). Whether you use apply () or call () depends entirely on the most convenient way to pass parameters to the function. If you are going to pass in the arguments object directly, or if you have an array that is first received in the function, it is certainly more convenient to use apply (), otherwise it may be more appropriate to choose call (). (It doesn't matter which method is used without passing arguments to the function).

4. Scope of expansion function operation

In fact, passing parameters are not the real place to apply () and call (); they're really powerful to be able to expand functions
The scope on which the operation depends. Let's look at an example.

Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
 alert (this.color);
}
Saycolor (); Red
Saycolor.call (this);//red
saycolor.call (window);//red
Saycolor.call (o);//blue

This example is modified on the basis of an example that describes the this object earlier. This time, Saycolor () is also defined as a global function, and it does show "red" when it is called in the global scope because the evaluation of This.color is converted to window.color evaluation. The Saycolor.call (this) and saycolor.call (window) are two ways to explicitly call a function in the global scope, and of course the result will be "red." However, when Saycolor.call (O) is run, the execution environment for the function is different, because the this object in the function body points to O, and the result is "blue." The greatest benefit of using call () (or apply ()) to augment the scope is that the object does not need to have any coupling with the method.

In the first version of the previous example, we first put the Saycolor () function in the object o and then call it through O, and in the example rewritten here, there is no need for the previous redundant step.

5. Bind () method

And finally, the bind () function, either call () or apply () is called immediately, and bind () does not, bind () generates a new function, and the bind () function has a parameter that is the same as calls (), and the first parameter is bound The value of this, followed by an indefinite argument passed to the function. When the new function generated by bind () is returned, when you want to tune 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 the object o, creating the Objectsaycolor () function. The This value of the Object-saycolor () function is equal to O, so you will see "blue" even if you call this function in the global scope.

Browsers that support the bind () method include ie9+, Firefox 4+, Safari 5.1+, Opera 12+, and Chrome.

Ii. call (), inheritance and callback of apply ()

Inheritance of Classes

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 ("Fools Wharf", 28, "male");

Test.alertname ()//Fool's Wharf

test.alertage ();//28

test.alertsex ();//Male

So that the Webdever class inherits the Person class, Person.call (this,name,age) means that the person constructor (also the function) is executed under the This object, so that Webdever has all the properties and methods of person. The test object is able to call the person's methods and properties directly

For callback
call and apply are also useful in the number of callback lines, many times we need to change the execution context of the callback function, most commonly used, such as Ajax or timing, in general, Ajax is the global, which is the window object, to see 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 (' album ' + THIS.name + ' belongs to ' + owner);

});

Over here

Album.get_owner (function (owner) {

 alert (' album ' + THIS.name + ' belongs to ' + owner);

});

THIS.name can be directly fetched to the name attribute in the album object.

Third, callback function

Talking about the callback function, many people know the meaning, but still a smattering. As for how to use, or a little confused. Some of the relevant online also did not say in detail what is going on, said more one-sided. Let me just say a little bit of personal understanding, Daniel, don't spray.

Defined
What's the callback?
Look at Wikipedia's Callback_ (computer_programming) Entry:

In computer programming, a callback are a reference to a piece of executable code this is passed as a argument to other CO De.

In JavaScript, the callback function is specifically defined as: function A is passed to another function B as an argument (a function reference), and this function B executes function A. Let's just say function A is called a callback function. If there is no Name (function expression), it is called an anonymous callback function.

As an example:

You have to go to the next bedroom to find classmates, found that people are not, how do you do?
Method 1, every few minutes again to visit the next bedroom, to see people in not
Method 2, please be with his roommate and see him call you when he gets back.
The former is polling, and the latter is callback.
Then you say, I directly in the next bedroom to wait for the classmate to come back?
Yes, it's just that you can save time to do other things and now you have to waste it waiting.
Turns the original non-blocking asynchronous call into a blocking synchronous call.
JavaScript callbacks are used in asynchronous invocation scenarios and use callback performance better than polling.
Therefore, callback is not necessarily used in asynchronous, general synchronization (blocking) scenarios are often used in the callback, such as the requirement to perform some operations after the callback function.

An example of using callbacks in a synchronization (blocking) to execute FUNC2 after func1 code execution completes.

var func1=function (callback) {
 //do something.
 (Callback && typeof (callback) = = "function") && callback ();
}

Func1 (FUNC2);
 var func2=function () {
}

Example of an asynchronous callback:

$ (document). Ready (callback);

$.ajax ({
 URL: "test.html",
 context:document.body
}). Done (the function () { 
 $ (this). AddClass ("Done ");
}). Fail (function () {alert (' error ');
}). Always (function () {alert ("complete"); 
});

When will the callback be executed?

Callback functions, which are generally executed in the context of synchronization, may not be executed in an asynchronous context because the event is not triggered or the condition is not satisfied. In addition, it is best to guarantee that a callback exists and must be a function reference or a function expression:

(Callback && typeof (callback) = = "function") && callback ();
Let's take a look at a rough definition "function A has a parameter, which is a function B, which executes function B when function A is done." Then the process is called a callback. This means that function B passes in function A in the form of a parameter and executes, in the order that a is executed first, then the parameter b,b is called a callback function. Let's take a look at the following examples first.

 Function A (callback) {
 alert (' a ');
 Callback.call (this);/or callback (), callback.apply (this), see a person liking
 }
 function B () {
 alert (' B ');
 }
 Call
 A (b);

The result is to eject ' a ' and then eject ' B '. So someone would ask, "What does it mean to write such a code?" It doesn't seem to have much effect! ”

Yes, but I also think it doesn't mean anything, "if you call a function, you call it directly in the function." I'm just writing a little example for you to make a preliminary understanding. There is very little in the process of writing code that has no parameters, because in most scenarios we pass parameters. Come with a parameter:

Function C (callback) {
 alert (' C ');
 Callback.call (this, ' d ');
 }
Call
C (function (e) {
 alert (e);
});

This call seems to be déjà vu, where the e parameter is assigned to ' d ', and we simply assign it to a character channeling, which can actually be assigned to an object. Is there an e parameter in jquery?

Use of callback functions

    • Resource loading: Dynamically loading JS files after the callback, loading the IFRAME to perform the callback, Ajax operation callback, picture loading complete execution callback, Ajax and so on.
    • DOM events and Node.js events are based on a callback mechanism (a Node.js callback may have problems with multi-tier callback nesting).
    • SetTimeout delay Time is 0, this hack is often used, settimeout called function is actually a callback embodiment
    • chained calls: when chained calls, it is easy to implement chained calls in the assignment (setter) method (or in a method that does not have a return value), and the accessor (getter) is relatively difficult to implement chained calls. Because you need to return the data you need instead of the this pointer, if you want to implement a chained method, you can use the callback function to implement the
    • The settimeout, setinterval function call gets its return value. Since two functions are asynchronous, that is: their call time sequence and the main process of the program is relatively independent, so there is no way to wait for their return value in the main body, they are opened when the program will not stop to wait, otherwise it will lose the meaning of settimeout and setinterval, So using return has no meaning, only use callback. The significance of the callback is to notify the agent function of the result of the timer execution to be processed in time.

When the implementation of the function 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, it becomes critical to use a callback function, such as an AJAX request. If you use a callback function for processing, the code can continue to perform other tasks without having to wait. In actual development, asynchronous calls are often used in JavaScript, and are even strongly recommended here!

Here's a more comprehensive example of using AJAX to load an XML file and using the call () function to invoke 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;
 Functional detection of IE for

 httprequest.onreadystatechange = function () {

 if (httprequest.readystate = 4 && Httprequest.status = = 200) {//state judgment
  Callback.call (httprequest.responsexml); 

 }

 ;

 Httprequest.open ("get", url);
 Httprequest.send ();
}

FN ("Text.xml", function () {//Call functions
 console.log (this); After this statement is output
});
Console.log ("This'll run before the above callback."); This statement first outputs

We request asynchronous processing, which means that when we start the request, we tell them to call our functions when they are done. In practice, the onReadyStateChange event handler also has to consider the failure of the request, where we assume that the XML file exists and can be successfully loaded 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 executes first because the callback function does not execute until the request completes.

The above is the entire content of this article, I hope to help you learn.

For more information please see: "Detailed JavaScript callback function"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.