Comparison and Analysis of call, apply, and bind usage in javascript

Source: Internet
Author: User

Comparison and Analysis of call, apply, and bind usage in javascript

This article mainly compares and analyzes the usage of the call, apply, and bind functions in javascript, which is very detailed. We recommend this article to our friends.

 

 

The usage of call, apply, and bind functions is a learning point that cannot be crossed by the javascript language. Next I will summarize their respective usage and common application scenarios.

First, let's look at the call function, which can be understood as "borrow", "request ". Imagine the following scenario: you are alone and want to make a phone call at home in an emergency. Unfortunately, your mobile phone is in arrears, or you are out of power, or you are out of the trap, in short, your mobile phone is useless. But you do not have to make this call, so you can borrow a friend's phone, borrow a neighbor's phone, or use a public phone, you can complete the call without using your mobile phone, but it doesn't matter who you call, the opposite is the same effect as using your mobile phone. The original intention of the call function is similar to that of this function. I will use the code below to simulate its Application Scenario:

 

The Code is as follows:


Var frog = {
Name: 'frog ',
Say: function (){
Alert (this. name );
}
}
Var rabbit = {
Name: 'rabbit'
}
Frog. say. call (rubbit) // rabbit

 

Rubbit is a dumb object, but it is impossible for him to name himself. Fortunately, it has a good friend named frog, it can talk. Therefore, rubbit requests frog to fulfill this wish for it. The first parameter of frog. say. call () must be the person who sends the request. Lawyers like to call it a principal. Here, the rubit request frog will say the name for it, so fill in the rubbit. In this way, when you say, you will find the rubbit name instead of the frog name. What Will frog look like? This is like asking yourself to do something, and feeding yourself salt can also be done. You can try:

 

The Code is as follows:


Var frog = {
Name: 'frog ',
Say: function (){
Alert (this. name );
}
}
Var rabbit = {
Name: 'rabbit'
}
Frog. say. call (frog) // frog

 

If you feed your bags of salt yourself, you must say your name. This is nothing surprising. Let's take a look at the typical call usage:

 

The Code is as follows:


// Convert the parameter into a real array object
Function frog (){
Var arr = []. slice. call (arguments );
Console. log (arguments. slice, arr. slice)
// Undefined function slice () {[native code]}
}
Frog (1, 2, 3, 4)

 

After such a call, we can use the arguments object as an array object. There are a lot of call usage. Open the jquery source code and you can easily find many places to use. I will not list them here, but return to our previous scenario. It is too simple to use a phone call. After making a call, I certainly want to bring something back. After all, I have been wandering around for so many years, if you don't honor the old man well, it must be an excellent job to buy a local specialty. However, the pressure of life outside the company is so great that we need to work overtime in addition to work every day. If we ask for leave, we will not only have to deduct the salary, but also spend a lot of road fees. The money will add up, it is estimated that it will be enough for the elderly to spend a year at home. It is not cost-effective to think about it, so I thought of the call function again. It is wise to ask it for help. Besides, it is free of charge, unlimited, and unlimited,. I will use the code to demonstrate it again:

 

The Code is as follows:


Var frog = {
Name: 'frog ',
Send: function (money, food, milk, suagate ){
Alert (money + food + milk + suagate );
}
}
Var rabbit = {
Name: 'rabbit'
}
Frog. send. call (rubbit, 'money', 'food', 'milk', 'suagate ')

 

If you have money, you can even send back several iPhone 6 plus items .. ^_^.

Now, the call is almost over. I don't know whether the above scene drama makes you understand what the call is. If it just starts your homesickness, I'm sorry.

Call also has a brother with the same parent and mother, called apply. If you understand the call usage, applying is actually the same thing. The only difference is that when applying doesn't like uploading, it seems troublesome to pack a single item, but it is not environmentally friendly. So he provides a big box for loading things. You just need to put all the things you want to pass in the box it provides. This big box is an array. In the above example, if you use apply, it is like this:

 

The Code is as follows:


Var frog = {
Name: 'frog ',
Send: function (money, food, milk, suagate ){
Alert (money + food + milk + suagate );
}
}
Var rabbit = {
Name: 'rabbit'
}
// Note the parameter differences
Frog. send. apply (rubbit, ['money', 'food', 'milk', 'suagate'])

 

The above is apply, and the call is past and present. But I never expected that the father of apply and call had made a fortune in real estate in the past few years, and there was another illegitimate child called bind outside. Although the two brothers call and apply are several years late, their abilities are not negligible. However, his identity is not recognized in some places. For example, IE6. I will use the code below to demonstrate his skills:

 

The Code is as follows:


Var name = 'rubbit ';
Var frog = {
Name: 'frog ',
Say: function (){
SetTimeout (function (money, milk ){
Alert (this. name + money + milk)
}. Bind (this, 'money', 'milk'), 1000)
}
}
Frog. say ();

 

Through comparison, we found that bind can be directly connected to function () {} for use. This is equivalent to saving both call and apply. You can specify the principal and parameters to be passed directly after the function. In terms of parameter passing style, it is more like calling.

For more information about bind, let's take a look at the Classic usage:

 

The Code is as follows:


Var obj = {
Name: 'frog'
}
Document. addEventListener ('click', function (){
Alert (this. name); // frog
}. Bind (obj), false );

 

To sum up, apply, call, and bind have the following similarities:

1. The first parameter is a set scope, that is, the website on which the task is performed.

2. All parameters can be passed

The difference is:

Apply and call are more compatible. Some earlier versions of bind are not supported.

Parameters passed by apply must be packaged with arrays, while call and bind are listed one by one.

Do you have a deeper understanding of the usage of call, apply, and bind functions? I hope this article will help you.

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.