Quickly understand the usage and use of apply () and call () in JavaScript __java

Source: Internet
Author: User

Before learning apply (), we have to understand the role of this and how to use it, and refer to my previous article, "Fast Understanding the usage and pitfalls of this in JavaScript." Of course if you are already familiar with this information, then

Please look straight down.

The function of call () and apply () is very similar, except for the difference in parameter types to accommodate different usage scenarios. They all exist to change the context in which the function is run, and, to be straightforward, to change

The point of this within the function.

Well. What the. I seem to hear you say change the point of this. That means that ...

That's right. This will enable inheritance. Exciting.

Look at the following code:

function Animal (name,food) {
   this.name = name,
    this.food = food,
   This.say = function () {
        Console.log ( name + "Likes" + This.food + '. ');
   }

function Rabbit (name,food) {
   animal.call (this,name,food);
}

var Judy = new Rabbit (' Judy ', ' Carrot ');

Judy.say ()//>>> Judy likes carrot.
As you can see, we've declared an object named Judy, and we don't add any properties and methods to the Rabbit object, but we use call () to inherit the properties and methods that originally belonged to Animal. We can do the animal function.

All the things that can be done.

How the hell did that happen? Let's look at the parameters of Call ():

The first one is an object that replaces the original this object in the function class, and we pass in this, remember, this is the object in the rabbit function that will instantiate the function in the future (I know it's a bit of a disagreement

When you declare Judy, this one refers to Judy.

In addition to the first argument, all subsequent arguments are passed to the parameters used by the parent function itself.

and the Apply () and call () function is almost the same, the only difference is that apply () the second parameter can only be an array, which is passed as a parameter to the argument list of the original function arguments.

In fact, in actual development, JS inheritance method is more than this one, the use of prototype chain inheritance is more commonly used, in addition to the constructor inheritance, here does not expand. and apply to use the scene, more use in such a scene:
You need to convert the array to a parameter list.

Apply () The attribute that converts an array to an argument list, and lets it do something interesting.

For example, the argument to the push () method can only be one or more arguments, not an array, and when we want to stitch array B to the end of array A, the traditional approach is to iterate over array B and push it back into the array A at a time,

This wastes the ability of push () to pass multiple parameters.

We can do this:

For example, the argument to the push () method can only be one or more arguments, not an array, and when we want to stitch array B to the end of array A, the traditional approach is to iterate over array B and push it back into the array A at a time,

This wastes the ability of push () to pass multiple parameters.

We can do this:

var list1 = [0,1,2];
var list2 = [3,4,5];
[].push.apply (LIST1,LIST2);

Console.log (List1);//>>> [0,1,2,3,4,5]
You look a little confused. You can understand this:
List1 calls the push method that belongs to the array object, which needs to pass in a list of arguments, and it happens that we have a list2 of the array type, and we do the concatenation.
The third line is equivalent to:
List1.push (3,4,5);
Look how magical it is to apply. Similarly, methods such as Max () and Min () under the Math object support only the argument list rather than the array, and you should have guessed it.

There are many places to apply () This feature brings a lot of convenience: such as functional programming in the currying (Corrie), apply () has an indispensable role.

Now that I'm talking about this, I'll take you to the next article. The function of Gerty.


Talking about the use of call (), apply (), bind () in JavaScript

Call (Thisobj,arg1,arg2 ...), apply (Thisobj,[obj1,obj2 ...]) These two methods are non-inherited methods that are included in each function

Call (thisobj[, args]) and apply (thisobj[, args))

The effect is the same, in simple terms, is to change the current object in which the method is used, pointing to the difference between the Thisobj object in the calling method (the first argument is the same) is the parameter passed in the call method is a

Each one is enumerated, and the argument in the Apply method is an array

Or an example to illustrate the more intuitive:

Window.color= ' Red ';
var o={color: "Blue"};
function Saycolor () {
alert (this.color);
};
Saycolor (); Red (global function, this is window)
Saycolor.call (this);//red (Invoke Call method, specify object is this, here is window, no point)
Saycolor.call (window);//red (Invoking the call method, specifying that the object is window, meaningless)
Saycolor.call (o);//blue (Calling the call method, specifying that the object is O, So this refers to Object o, where the original window points O)
saycolor.apply (o);//blue (call method is invoked, the specified object is O, so this refers to Object o, where the original window points to O)
The bind () method in ECMAScript5 is similar to the first two methods, and the bind () method creates an instance of a function that is bound to the value passed to the bind () function
function A (Y) {return
this.x+y;
};
var o={x:1};
var g=a.bind (o);
g (2);//3
You can see from the example that function a binds to the object o, and returns the new function g, when called G, the A function is called as the object O method.
Bind () This method binds a function to an object and returns a new function in which the parameters passed in are passed on to the bound function.
Let's look at their differences.
In JS, these three are used to change the function of this object to point to, they have what kind of difference.
Before you say the difference, let's summarize the similarities between the three:
1, are used to change the function of this object to point to.
2, the first argument is the object to point to.
3, all can use the subsequent parameters to pass the parameter.

So where are their differences, first look at an example.
var XW = {
Name: "Xiao Wang",
Gender: "Male",
Age:24,
Say:function () {
Alert (THIS.name + "," + This.gender + ", this year" + this.age);
}
}
var xh = {
Name: "Little Red",
Gender: "Female",
Age:18
}
Xw.say ();

There is nothing to say in itself, the show is definitely Xiao Wang, male, 24 this year.
So how to use the XW say method to display the XH data.
For call you can do this:

Xw.say.call (XH);
For apply, you can do this:

Xw.say.apply (XH);

And for bind, you need this:

Xw.say.bind (XH) ();
If you write Xw.say.bind directly (XH) there will be no results, see the difference. Call and apply are both direct calls to a function, and the Bind method returns a function, so you need to () to invoke it later.
So what's the difference between call and apply? Let's rewrite the example a little bit.
var XW = {
    name: "Xiao Wang",
    Gender: "Male",
    age:24,
    say:function (school,grade) {
        alert (this.name + "," + This.gender + ", this year" + This.age + ", on" + School + + "+ grade);                
    }
var xh = {
    name: "Little Red",
    Gender: "Female",
    age:18
}
You can see that the say method has two more parameters, we pass the parameters of the call/apply.
For call, that's it.
Xw.say.call (XH, "Experimental Primary School", "Six Grade");       
And for apply, that's it.
Xw.say.apply (xh,["Experimental Primary School", "six grade Zhengzhou Psoriasis Hospital"]);
See the difference, the argument behind call is one by one corresponding to the Say method, and the second argument to apply is an array, and the elements in the array correspond to one by one of the Say method, which is the biggest difference.
So how does bind get involved? It can be passed as call.
Xw.say.bind (XH, "Experimental Primary School", "Six Grade") ();
But since BIND is still returning a function, we can also invoke the argument at the time of the call.
Xw.say.bind (XH) ("Experimental Primary School", "Six Grade");
The above mentioned is the entire content of this article, I hope you can enjoy.
Related Article

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.