This article is really difficult to write, because there are numerous articles on the Internet. coincidence is a few days ago to see the teacher Ruan an article of a sentence:"For me, blogging is primarily a knowledge management tool, followed by a communication tool. My technical articles are mainly used to sort out the knowledge I don't know. I write only those things that I have not mastered fully, those I am proficient in, often have no motive to write. Showing off is never my motive, curiosity is. "for this sentence, can not agree to more, but also let me make up my mind to write this article, online articles, although most of the copy and paste, and obscure difficult to understand, I hope that through this article, can clearly improve the apply, call, bind understanding, and list some of their magical use to deepen memory. Apply, callin JavaScript, call and apply are meant to change the context in which a function is run, in other words, to change the direction of this within the function body. A major feature of JavaScript is the notion that a function has a " context of Definition " and a " runtime context " and a " context can be changed ." First, a chestnut:
function fruits () {}fruits.prototype = {color: "Red", Say:function () {console.log ("My color is" + This.color);}} var Apple = new Fruits;apple.say ();//my color is red
But if we have an object banana= {color: "Yellow"}, we don't want to redefine it say method, then we can use call or apply with Apple's say method:
Banana = {color: ' Yellow '}apple.say.call (banana);//my color is yellowapple.say.apply (banana);//my color is yellow
So, you can see that call and apply are to change this dynamically, when an object does not have a method (this pest banana no say method), but the others have (this pest Apple has say method), We can use call or apply to manipulate other object methods.
the difference between apply and call
For both apply and call, the function is exactly the same, except that the parameters are accepted in a different way. For example, there is a function defined as follows:
var func = function (Arg1, arg2) {};
You can invoke the following method:
Func.call (This, arg1, arg2); Func.apply (This, [Arg1, arg2])
Where this is the context you want to specify, he can be any JavaScript object (everything in JavaScript), call needs to pass parameters in order , and apply is to put the parameters in the array .
in JavaScript, the number of arguments for a function is not fixed, so if you want to apply the condition, call is used when your parameters are clearly known. use apply when unsure, and then pass in the parameter push into the array. When the number of arguments is indeterminate, the function can also traverse all the arguments by arguments the array. to consolidate your memory, here are some common uses:1. Append between arrays
var array1 = [N, "foo", {name "Joe"}, -2458]; var array2 = ["Doe", 555, +]; Array.prototype.push.apply (Array1, array2); /* Array1 value for [+, ' foo ', {name ' Joe '}, -2458, ' Doe ', 555, 100] */
2. Get the maximum and minimum values in the array
var numbers = [5, 458, -215]; var maxinnumbers = Math.max.apply (Math, numbers),//458maxinnumbers = Math.max.call (math,5, 458, 120,-215);//458
Number itself does not have the Max method, but with Math, we can use call or apply its methods.
3. Verify that it is an array (provided the ToString () method has not been rewritten)
Functionisarray (obj) { ReturnObject.prototype.toString.call (obj) = = = ' [Object Array] ';}
4. Class (pseudo) array using array method
var domnodes = Array.prototype.slice.call (document.getElementsByTagName ("*"));
there is an object structure called a pseudo-array in JavaScript. In particular, arguments objects , as well as calls to getElementsByTagName , document.childnodes and the like, they return NodeList objects are pseudo-arrays. You cannot apply the push, pop, and other methods under the array. but we can convert the object with the length property to the real array by Array.prototype.slice.call, so that domnodes can apply all the methods under the array.
in-depth understanding of applying apply, call
below to borrow an interview question , to go deeper to understand the next apply and call.
Define a log method that allows it to proxy the Console.log method, and the common workaround is to:
function log (msg) { console.log (msg);} Log (1); 1log (up to); 1
The above method can solve the most basic requirements, but when the number of incoming parameters is not deterministic, the above method is invalid, this time you can consider using apply or call, notice here how many parameters are indeterminate, so using apply is the best, Here's how:
function log () { console.log.apply (console, arguments);}; Log (1); 1log (up to); 1 2
The next requirement is to add a "(app)" prefix to each log message, such as:
Log ("Hello World"); (APP) Hello World
What should be more elegant? This time you need to think that the arguments parameter is a pseudo-array, converted to a standard array by Array.prototype.slice.call, and then using the array method Unshift, like this:
function log () { var args = Array.prototype.slice.call (arguments); Args.unshift (' (app) '); Console.log.apply (console, args);};
Bind
Finish the Apply and call, and then say bind. The bind () method is similar to apply and call and can also change the direction of this in the function body.
The MDN explanation is that the bind () method creates a new function called a binding function that, when called, binds the binding function to the first parameter of the bind () method as it is created when it is passed into bind () The second and subsequent parameters of the method plus the arguments of the binding function itself are invoked in order as parameters of the original function to invoke the original function.
Take a look directly at how to use it, in common monomer patterns, we usually use _this, that, self, and so on to save this, so that we can continue to reference it after changing the context. Like this:
var foo = {bar:1,eventbind:function () {var _this = this;$ ('. SomeClass '). On (' click ', Function (event) {/* ACT on the event */console.log (_this.bar);//1});}}
Due to Javascript-specific mechanisms, the context is transitioning to $ ('. SomeClass ') in Eventbind:function () {}. On (' click ', Function (event) {}) has changed, These methods of saving this with variables are useful and have no problem . Of course, using bind () can solve this problem more gracefully:
var foo = {Bar:1,eventbind:function () {$ ('. SomeClass '). On (' click ', Function (event) {/* Act on the event */console.log (thi S.bar);//1}.bind (this));}}
In the above code, bind () creates a function that, when the Click event is bound to be invoked, its this keyword is set to the value passed in (this refers to the parameter passed in when bind () is called). So here we pass in the desired context this (actually foo), into the bind () function. Then, when the callback function is executed, this points to the Foo object. One more simple chestnut:
var bar = function () { console.log (this.x);} bar ();//Undefinedvar func = Bar.bind (foo); func ();//3
Here we create a new function func, when it is executed by using bind () to create a binding function, it will be set to Foo instead of the global scope as we call Bar ().
Apply, call, bind comparison
So what are the similarities and differences between apply, call, and bind? When to use apply, call, and when to use bind. Simple one of the chestnuts:
var obj = {X:81,};var foo = {getx:function () {return this.x;}} Console.log (Foo.getX.bind (obj) ());//81console.log (Foo.getX.call (obj));//81console.log (foo.getX.apply (obj));// 81
All three outputs are 81, but note that with the bind () method, he has more pairs of parentheses behind him.
That is, the difference is that the bind () method is used when you want to change the context and not execute immediately, but rather when the callback executes. The Apply/call executes the function immediately.
Let's summarize:
- Apply, call, and bind are all pointers to the This object that is used to change the function;
- Apply, call, bind the first parameter is the object that this is to point to, that is, the context you want to specify;
- Apply, call, bind three can use the following parameters to pass the parameter;
- Bind is to return the corresponding function, which is convenient to call later; apply, call is called immediately.
All the code that appears in this example is available for download on my github.
Original article, writing Limited, Caishuxueqian, if there is not in the text, million hope to inform.
"Elegant Code" in the magic of JavaScript, apply, call, bind