A comparative analysis of the usage of call,apply,bind in JavaScript

Source: Internet
Author: User

This article mainly gives you a comparative analysis of JavaScript in the use of Call,apply,bind three functions, very detailed, recommended to small partners.The use of the three functions of Call,apply,bind is a point of learning that the language of JavaScript cannot be crossed. I'm going to take a good look at them. Their respective usages and common application scenarios.

First, the call function can be interpreted as "borrowing" and "requesting". Imagine the following scenario: You are lonely wandering outside, there is an urgent need to call home, but unfortunately, the mobile phone owes a fee, or no electricity, or fall out of the pit, in short, your phone is not used. But you have to call this phone, so you can borrow a friend's cell phone, or borrow a neighbor's mobile phone, or a public telephone, so you can do not have a mobile phone available, the completion of the phone call this thing, and as to who you are using the phone, it is not important, Anyway, the same effect as the phone call on your own phone. Call this function is also similar to the original intention, below I use the code to simulate its application scenario:

Copy CodeThe code is as follows:
var frog = {
Name: ' Frog ',
Say:function () {
alert (this.name);
}
}
var rabbit = {
Name: ' Rabbit '
}
Frog.say.call (rubbit)//Rabbit

Rubbit This object is a dumb bar, but he wants to say his name, light on its own ability, is impossible to achieve, fortunately, it has a good base called frog, it can talk. So, Rubbit asked Frog to fulfill this wish for it. The first parameter of Frog.say.call () must be to fill out the person who made the request, which the lawyer likes to call the principal. Here is Rubbit request frog for it say name, so fill in rubbit. In this way, when say, you will find the name of Rubbit, not the name of frog. What would it be like to fill out frog here? It's like asking yourself to do something, and it's also possible to feed your own salt. You can try it:

Copy CodeThe code is as follows:
var frog = {
Name: ' Frog ',
Say:function () {
alert (this.name);
}
}
var rabbit = {
Name: ' Rabbit '
}
Frog.say.call (Frog)//Frog

Self-feeding bags of salt, it must be said his name, this is nothing unexpected. Let's take a look at the classic use of call:

Copy CodeThe code is as follows:
Convert parameters to real array objects
function Frog () {
var arr = [].slice.call (arguments);
Console.log (Arguments.slice,arr.slice)
Undefined function slice () {[native code]}
}
Frog (1,2,3,4)

With such a call, we can use the arguments object as an array object. About the use of call many, open the source of jquery, it is easy to find a lot of use of the place. Not listed here, or back to our front of the scene, to borrow the phone is too simple, after the call, definitely want to take something back, after all, so many years of wandering outside, no good filial piety under the old man, buy some local products back, it is certainly very good. But outside the life pressure is so big, every day in addition to work overtime, if leave, not only wages to buckle, but also to spend a lot of money, which add up, estimates are enough for the elderly at home for a year of use. Think not cost-effective, and then think of call this function, please it to help, take it back is very wise choice, and it does not charge, unlimited, no limit, how many, with how much. I'll use the code again to illustrate:

Copy CodeThe 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 are rich and headstrong, you can even send a few iphone6 plus something back: ^_^.

Speaking of which call is almost over, I do not know the above melodrama, is not to let you understand the call is how, if only to remind you of homesickness, then I apologize.

Call also has a half brother, called apply, if you understand the use of calls, then apply is actually the same thing, the only difference is that apply does not like to pass things, a thing hit a bag, it seems very troublesome not to say, but also not environmental protection. So he provides a big box for things, and you put everything you want to preach in the box it provides. This big box is an array. The above example, if you do it with apply, is this:

Copy CodeThe code is as follows:
var frog = {
Name: ' Frog ',
Send:function (money,food,milk,suagate) {
alert (money+food+milk+suagate);
}
}
var rabbit = {
Name: ' Rabbit '
}
Notice the difference between the parameters
Frog.send.apply (rubbit,[' money ', ' food ', ' milk ', ' suagate '))

The above is Apply,call's past life. But never thought, apply and call of the father, some years ago to make a fortune, in the outside there is a bastard called bind. Although the two elder brothers of call and apply have a few years to debut, but the ability is not to be underestimated. But his identity, in some places, is not recognized. Like IE6. Below I still use the code to demonstrate his ability:

Copy CodeThe 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 ();

By contrast, bind can be directly attached to function () {}. The equivalent of both call and apply are saved, directly after the function to specify the principal and the parameters to be passed. From the style of communication, more like call some.

For bind, let's look at a classic usage:

Copy CodeThe code is as follows:
var obj = {
Name: ' Frog '
}
Document.addeventlistener (' click ', function () {
alert (this.name); Frog
}.bind (obj), false);

To summarize, Apply,call,bind, the same points of the three brothers are:

1. The first parameter is the state scope, that is, on whose site the work is done.

2. All parameters can be passed

Different points are:

Apply,call compatibility is better, bind some of the lower version of the browser is not supported.

The arguments passed by apply must be wrapped in an array, while call and Bind are listed by the parameters to be passed.

Whether we have a more in-depth understanding of the use of Call,apply,bind three functions, I hope this article can help you.

A comparative analysis of the usage of call,apply,bind in JavaScript

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.