Apply, call, bind differences, usage

Source: Internet
Author: User

Both apply and call exist to change the context in which a function is run (just to change the direction of this inside the functionIf you use the Apply or call method, then this points to their first argument, and the second parameter of apply is an array of arguments, and the second and subsequent parameters of call are the elements of the array, meaning they are all listed; Common usage: 1. Append between arrays; 2. Get the maximum and minimum values in the array, and use them to extend the scope to have the Min and Max methods of math; Since no object calls this method, the first argument can be written null or by itself; var numbers = [5, 458, 120, -215];
var maxinnumbers = Math.max.apply (Math, numbers),//458 maxinnumbers = Math.max.call (math,5, 458, 120,-215); 4583. Verify that it is an array (provided that the ToString () method has not been rewritten) function IsArray (obj) {
return Object.prototype.toString.call (obj) = = = ' [Object Array] ';} 4. Methods that let an array of classes have arrays such as arguments objects, get to the document node, etc., and have no array of those methods: Array.prototype.slice.apply (argument); In theory this is faster, looking directly at the slice method on the prototype//but actually slower or [].slice.apply (arg uments); In theory, this is slow, because to do an instantiation of the array to find the slice method//is actually relatively fast, because the various automation tools now will convert the previous method to this, and the second code is relatively concise, So it will be faster; bind ()--also changes the direction of this in the function body; bind creates a new function called a binding function, and when called, the binding function passes the first parameter of the bind () method as this when it is created. The second and subsequent arguments to the bind () method plus the arguments of the binding function itself are invoked as arguments to the original function, and the main difference between bind and apply and call is that bind will not be called immediately, and the other two will immediately invoke the example: If bind is called multiple times, So the number of times out is not valid, three differences in usage:are used to change the direction of the This object of the function, the first parameter is the object to which this is to be pointed, the parameter can be used for subsequent arguments, BIND is the return function, it is convenient to call later, apply, call is called immediately;

http://blog.csdn.net/u014267183/article/details/52610600

original September 21, 2016 17:32:57
    • Label:
    • JavaScript/
    • Context Binding
    • 4753

Before looking at a point es6 arrow function, in order to understand the arrow function this, read a lot of articles, also by the way to see a few binding functions, found a lot of problems not noticed before, harvest a lot.

Before on the online written questions to see the use of JS to implement the bind () function, do not care, thought that since all are used for context binding, with call or apply should be able to achieve. Now look, I still pattern Tucson broken.

First of all, call () and apply (), for these two functions, I am looking at their own books to learn, learning when there is no problem, but I checked the internet on the call () and apply () article, Ah, this is what AH!! It's hard to watch.

In fact, call () and apply () change the execution context of the function, which is the this value. Both of them are methods of function objects, each of which can be called. Their first parameter is the execution context you want to specify, and the second is used to pass arguments (say the second one is inaccurate, the second part, because arguments can be passed multiple), which is the arguments to the function that invokes the call and apply methods. To put it bluntly, call the function, but let it execute under the context you specify, so that the scope that the function can access changes. The following code:

function Apply1 (NUM1, num2) {
Return sum.apply (this, [Num1, num2]);
}
function Call1 (NUM1, num2) {
Return Sum.call (this, NUM1, num2);

}

Here, our execution environment passes this, which means that the execution context of the function is not changed. These two pieces of code just want to tell you the difference between call and apply.

The second part of the call parameter should be one pass, apply to put these parameters into the array. This is the difference between them, really so little difference!!!

Then, one thing to say: Their second argument can be arguments.

—————————————————————————————————————————————————————————————————————————————

The bind () function, bind () is the method in Es5, and is used to implement context binding, which is known as the function name. Bind () and call are different from apply. Bind is a new function that is created, binds its context to a parameter in the bind () bracket, and then returns it.

Therefore, after bind, the function does not execute, but only returns a copy of the function that changed the context, while call and apply are directly executing the function.

The following code reflects this, and also shows the use of bind (the code is taken from Zhang Xin's blog)

var button = document.getElementById ("button"),    text = document.getElementById ("text"); Button.onclick = function ( {    alert (this.id);//Eject Text}.bind (text);

However, because IE6~IE8 does not support this method, so if you want to use in these several browsers, we need to simulate the method, which is also the interview frequently test questions, the simulation code is as follows:

if (!function () {}.bind) {    Function.prototype.bind = function (context) {        var = this            , args = Array.protot Ype.slice.call (arguments);                    return function () {            return self.apply (Context, Args.slice (1));}}    ;}
This is the code that corrects a mistake I've been having for a long time. Let's take a look at this code

First, we determine if there is a bind method, and then, if it does not exist, add a custom bind method to the prototype of the function object.

In this case, the var self = This code bothers me, supposedly, prototype is an object, and the object's this should point to the object itself, that is, prototype, but really. Take a look at the following code:

function A () {};

A.prototype.testthis = function () {console.log (A.prototype = = this);};

var B = new A ();

B.testthis ();//false

Obviously, this does not point to prototype, and after testing it does not point to a, but to B. So the this value in the prototype is clear. Point to the object that called it.

Array.prototype.slice.call (arguments);
Next is the code above, which converts a variable of a class array into a real array. Why, in fact, the book does not say that slice also have such a usage, do not know who invented it. The use of slice can be checked on the Internet to find out. But to correct a point, the introduction of the internet said slice has two parameters, the first parameter can not be omitted. However, I do not know that I understand the question or the ground, the above code TMD is not typical of the parameters do not pass!!! Arguments is the context passed to call, as mentioned earlier, do not confuse (because arguments has no slice method, this belongs to the slice method that borrows the array prototype). And after testing, if you do not give the slice parameters, it is equivalent to pass a 0 to it, the result is to return a copy identical to the original array.

The code after this is very well understood and returns a function that takes the first argument passed to bind as the execution context, since args is already an array, excludes the first item, passes the following part as the second part argument to apply, and says the use of apply.

So, our own bind function behaves just like bind in ES5.

Apply, call, bind differences, usage

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.