Brother Tai Propitiate, about arguments, your idea is the same as the great god----Chat the Apply and call in JS

Source: Internet
Author: User
Tags ming

JavaScript provides application and call two invocation methods to determine the direction of this in the function body, which is characterized by the way in which objects can ' borrow ' other objects.
Some of the previous blogs reviewed some of the Web control development methods, and we talked about how to implement a custom combo box, as well as a relatively complex address control development, starting with the previous one, beginning with the topic of the JavaScript language itself, recalling closures and prototype inheritance, Today we're going to talk about the two ways in which apply and call are called.
Of course, although the subject is changing, the writing style of analyzing theoretical knowledge based on business scenario will not change.
Let's start with an example of life:
Xiao Ming Home has fruit, also has a ' juice machine ', Little red home also has fruit, but no juice machine. One day, Little Red also want to squeeze fruit into juice to drink, at this time, Little Red will how to do it? Of course, Xiao Hong can "borrow" Xiao Ming's Juice machine to use, and then go back, because when not in their own home also occupy the place, the next to use, then to borrow is, because ' mutual help ' is the JavaScript community
Let's take a look at how to use JavaScript to illustrate this situation:

 var  xiaoming = {name:  ' xiaoming ' , fruit:  ' orange '  function   () {Console.log ( ' pressing: ' + this . Fruit + ' juice! '    ); }}  var  xiaohong = {name:  ' Little Red ' , fruit:  ' apple ' }xiaoming.makejuice ();  //  output: squeezed: The orange juice of Xiao Ming's house!   xiaoming.makeJuice.apply (Xiaohong); //  output: being squeezed: the apple juice of the Little red house! 

The core meaning of the Apply method is this, obviously, if there is no reference to this at all in a function body, is it also lost the meaning of invoking apply? This is not the case, and sometimes it is necessary to process the incoming parameters.

Further, if the called function needs to pass arguments, how do you handle the call to apply? Let's take a look at the above example, assuming that when you squeeze the juice, you need to pass in the parameters: The amount of water added and how long it will be pressed.
How do I use apply at this time?

varXiaoming ={name:' Xiao Ming ', Fruit:Orange, Makejuice:function(water, time) {Console.log (' Being squeezed: ' + This. Name + ' home ' + This. Fruit + ' juice, add water: ' + water + ' ML, spents: ' + Time + ' minutes. ‘); }}varXiaohong ={name:' Little Red ', Fruit:Apple}varTask_info = [500, 1];//Put the parameters you want to pass in an arrayXiaoming.makeJuice.apply (Xiaohong, task_info);//output: Pressing: Red home apple juice, add water: ML, Time: 1 minutes. 

Analysis
When using the Apply method with a function:

    • The 1th parameter is Thisobject, which takes the incoming thisobject instead of the pointer to this in the function body.
    • The 2nd parameter passes in an array, and the function replaces the argument list with the value of the array.

Back to the example above, the equivalent of this scenario:

Xiao Hong: Xiao Ming, please squeeze the apple juice for me. Xiao Ming: Yes, you can take my juice machine and use it.     you have to figure it out before you use it.  ' prepare to add water and squeeze a few minutes '  . Xiao Hong: ok. 

Small red to squeeze the juice machine to take, first put the ' add 500mL water, squeeze 1 minutes ' content write to ' paper ', prepare the raw materials, press ' paper ' on the information operation Juicer, to avoid rush. the ' paper ' used to write task-related information is equivalent to the array used to pass the parameter list information when the Apply method is called.

When it comes to the argument list, it's natural to think of arguments, when the function is called, the runtime environment of the function automatically generates a variable arguments to the argument list. A lot of the data will say that arguments is a ' class array ' (pseudo-array) with some attributes of the array. So, when invoking a function using the Apply method, can the 2nd parameter passed in as a ' class array ' (pseudo-array) like arguments?
We construct a scene to verify, the recent community has moved to a king grandmother, one day Wang Grandma also want to drink juice, she knew Xiao Ming home has juicer, originally wanted to find Xiao Ming help, but xiaoming business. Xiao Ming and Grandma Wang said, you want to have a small amount of juice and how long you want to play, find little red to help on it.
Now, we come to the realization of such a scene, the focus is on Grandma Wang to help Red's function.

varWang ={name:' Grandma Wang ', Helpfromxiaohong:function(water, time) {//Little Red himself does not have juicer, or to use the juicer machine, using the Apply method call function        //Grandma Wang's request is exactly the same as the ' task content ' to be prepared when using the juicer,        //So, here, just pass in arguments and see        //As for fruit, little red of course not to Grandma Wang, just use their own home        //Thus, the invocation is as follows:xiaoming.makeJuice.apply (Xiaohong, arguments); }}wang.helpfromxiaohong (400, 2);//The old man didn't drink much, but he wanted to break the fruit a little .//output: Pressing: small red home apple juice, add water: Three ML, Time: 2 minutes. 

The discovery is exactly the same as what we expected, which means that the second parameter passed in apply
can also be a ' class array ', the most common of course is to directly pass arguments as the 2nd parameter.
Characteristics of ' class array ':

    • Has a length member that ' represents ' the number of elements contained '.
    • The ability to retrieve its members with a number such as a-D.

By now we have had some knowledge of the method of apply invocation, and then we return to our daily work. We often see this method of invocation:

var w = Array.prototype.shift.apply (arguments);

what does this line of code mean? Perhaps we all know that the first parameter value of the implied ' class array ' arguments is removed, then assign to the variable W.

Thinking

1. Why not call the shift function directly with arguments?

Because arguments is not a true ' array ', from the language features of JavaScript, arguments is simply an object with some ' array features '. It is not created by the new Array () and its prototype chain is not linked to ' array.prototype ', so you cannot use the shift () function directly.
"By, since the language comes with the east, why not directly design the group?" Make me want to use the array of the relevant methods to have to turn a corner. "
Brother Taiwan Propitiate, in fact, this is not a person to think of you, including the Master of JavaScript (Douglas Crockfod) also think so, is the so-called great minds.

2. How to understand var W = Array.prototype.shift.apply (arguments); What about this statement?

We learned that, according to the invocation pattern of apply, it would replace this in the function body with the 1th parameter passed in. From this point of view, this is replaced by the arguments object (a special object with an ' array ' feature) in the Array.prototype.shift.

We know that it's no problem to call shift with an array object.
For example:

// Output: A

Because in the call process of [' A ', ' B ', ' C '].shift (), no parameters are passed in, so you can infer that this is definitely referenced in the Array.prototype.shift function body. by This.length and This[0] this way of processing to calculate the results of the operation,

Obviously, this particular object arguments for Arguments.length and arguments[0] is no problem, it can reflect its ' array characteristics ', so, by calling Array.prototype.shift.apply (arguments), you can get the value of the 1th parameter passed in.

In order to increase the ' screen sense ', we put it in front of Grandma Wang's function of asking for help:

var wang = {    ' Grandma Wang ',    function(water, time) {        var w = Array.prototype.shift.apply (arguments);        ' Grandma Wang wants to drink ' + W + ' ml of juice. ' );          Xiaoming.makeJuice.apply (Xiaohong, arguments);        }    }    400, 2);  

> Expected output:
Grandma Wang wants to drink the juice of the ML.
Pressing: Red home apple juice, add water: Three ML, spents: 2 minutes.
> Actual output:
Grandma Wang wants to drink the juice of the ML.
Pressing: Red home apple juice, add water: 2 ML, spents: undefined minutes.

Analysis

1. For the conclusions we have just tried to verify, we have found that our assumptions are correct. The arguments object successfully ' borrowed ' the shift function of the array, so the output: Grandma Wang wants to drink the juice of ML.
2. However, in the following call, incredibly output is: being squeezed: Little Red Home apple juice, add water: 2 ML, spents: undefined minutes.

This is a good understanding, the function of the shift function is: ' Popup ' array of ' 1th element ' and return. This means that after var w = Array.prototype.shift.apply (arguments), after the call, the contents of arguments also changed, Arguments[0] value is not 400!

This is also explained once again:

    • The invocation of apply, in addition to replacing the point of this in the body of the function, does not change any other logic of the function. The effect of the ' borrowing ' function is the same as the object's own function.
    • Arguments this ' similar array ', other than the ' archetype inherits from ' Array.prototype, the other features and arrays are the same.

3. In just the scenario, if you really need to call xiaoming.makeJuice.apply (Xiaohong, arguments), before showing how many ml Grandma Wang wants to drink, call var w = arguments[0]; If you can, why do you want to ' play ' someone else?

The complete example is as follows:

varXiaoming ={name:' Xiao Ming ', Fruit:Orange, Makejuice:function(water, time) {Console.log (' Being squeezed: ' + This. Name + ' home ' + This. Fruit + ' juice, add water: ' + water + ' ML, spents: ' + Time + ' minutes. ‘); }}varXiaohong ={name:' Little Red ', Fruit:Apple}varWang ={name:' Grandma Wang ', Helpfromxiaohong:function(water, time) {varW = arguments[0]; Console.log (' Grandma Wang wants to drink ' + W + ' ml of juice. ‘ );        Xiaoming.makeJuice.apply (Xiaohong, arguments); }}wang.helpfromxiaohong (400, 2);

Finally, we add a feature: if we are using the Apply Call method, the 1th parameter is passed to NULL, but the function body of the ' borrow ' function itself uses this, then, will it be reported as abnormal? because it is certainly not possible to write null.name in such a way directly. Here is not suspense, first put the answer here. The answer is: no exception is reported.
Say after a few days, Wang Grandma again want to drink juice, and then to Xiao Ming call, but Xiao Ming is still on business, so Xiao Ming also called Grandma Wang to find Little red help, in addition, Xiao Ming also gave small red dozen a phone to explain the situation. This back to Xiao Ming's phone, Little Red may be a little reluctant, thought: ' Xiao Ming who are you? Good fame you come to take, trouble me to do. In spite of some discomfort in the heart, but after all, is a warm-hearted good girl, Wang Grandma's busy or help, but this time, she can not take their own fruit to squeeze, but directly with the community of fruit.

Back to Grandma Wang's help function, since no Xiaohong home fruit, you don't have to pass in Xiaohong this object, pass a null try.

Xiaoming.makeJuice.apply (Xiaohong, arguments);

Modified to:

null , arguments);

and add the following variables at the beginning of the code:

var name = ' Community '; var fruit = ' watermelon ';

At this point, the output is as follows:
Grandma Wang wants to drink the juice of the ML.
Being squeezed: watermelon Juice in the community , add Water: 2 ML, Time:.

That is, if the first parameter passed in is null, then this in the body of the function points to the global object, which is the window in the browser (this is the effect in the Chrome browser). Obviously, if this is used in the body of the function, and you invoke it in the Apply mode, pass a null to it in the past, this is a ' little red classmate angry ' behavior, not a good habit.

So, for the method of apply invocation, we can summarize the following:

    1. If this is explicitly used in the function body of a function, it should be passed to an explicit Thisobj object, and the object should contain related properties. Similar to the "juicer" to lend you a good, you can not even fruit is not ready?
    2. If a function is of type ' tool ', you can pass in a null as Thisobject when using the Apply Call method. Similar to the ' Fruit knife ', what is the fruit that is placed on the wrapped board when used, what it cuts, and what does the man with the fruit knife have not a half-dime relationship.

A common usage scenario for the second scenario is that the interface of the function requires passing in a ' parameter list ', but you have only one array at hand.
For example: Want you to call Math.max (2, 10, 6, 1) like this; However, you have only one array of [2,10,6,1] in hand.
-If you call Math.max directly ([2,10,6,1]); Will output Nan. Because Math.max will assume that the first parameter [2,10,6,1] is not a number at all.
-or you can do this:

var test_array = [2,10,6,1]; Math.max (test_array[0], test_array[1], test_array[2], test_array[3]);

Obviously, this way is practicing typing, not ^_^ the program ~ ~

[Parameter list] and [array],[array] and [parameter list].......apply call way can not be converted, so we can do this:

var test_array = [2,10,6,1]; Console.log (  null , Test_array));  // Output: Ten     

Output the results we expected: Ten, Yes, that was it.

If Little red also do not use the fruit of the community, directly with the fruit of Xiao Ming's home? It does not need to be called with the Apply method, directly in the following way:

Let's take a look at this time of Grandma Wang's help function:

var wang =' Grandma Wang 'function(water, time) {     var w = arguments[0< c7>];     ' Grandma Wang wants to drink ' + W + ' ml of juice. ' );      Xiaoming.makejuice (arguments);   }}

Look at the function name is Helpfromxiaohong (get help from small red), actually it is Xiaoming.makejuice (Xiao Ming is providing help). We have a vague sense of some ' design patterns '. We'll talk about the design mode next time.

Today's topic is to talk about here ...

What the? I haven't talked about call yet!

Almost forget that thedifference between the call mode and the Apply method is mainly reflected in the parameters of the incoming form is not the same , when the invocation calls, the 1th parameter is passed to Thisobject, the 2nd parameter and the following parameters make up the ' argument list ' passed to the function.
For example:
When called with the Apply method, we write this:

var task_info = [400,2];xiaoming.makejuice.apply (Xiaohong, task_info);

When called by call, we write this:

Some people say that the call invocation is actually implemented using the Apply method, similar to defining a member function call for Function.prototype. We don't know how the JavaScript engine is going to work, but the way the call is not mentioned in his book from the JavaScript big-road, we can only understand the way the application is invoked, and we know that the difference between the form parameter and the Apply , maybe you can.

The difference in formal parameters, we can then use an example of life to understand:

Xiao Ming often go to Korea on business, Little Red, often entrusted to help Xiao Ming to bring some cosmetics in Korea. Usually before Xiao Ming business trip, Little Red will buy the cosmetics written in a list (equivalent to: Apply mode to put the parameter values into an array), Xiao Ming to the South Korean shopping malls, as long as the shopping list to buy a comparison can be, equivalent to the application (apply) This shopping list, This is how the Apply is invoked.
However, on one occasion, Xiao Ming because of the short travel time, did not tell Xiao Red, quickly returned to the airport, received a small red phone calls (call), yes, is the Little red call came over. "dead, go to Korea on business trip also do not say a voice!" Are you deliberately hiding from my aunt?! "You listen to me, it's not too short, I'll be home soon, and now it's almost time for Busan airport." "I have to buy it at the airport now!" You listen to what I want to buy! "Well, I'm going to buy it for you now, and you say what you want to buy." " Obviously, Xiao Ming's hand is not a clear shopping list, time is so tight, it is impossible to first tidy up a list to go to the mall to buy." So, Xiao Ming went to the mall, listening to the small red phone, Xiao Red said one, Xiao Ming on the corresponding merchandise to the shopping cart, which is the call way.

Summary

In this paper, we explain the value and usage of the application invocation method of the function, and combine the common usage scenarios to explain some features of the arguments object implied in the function body, and also explain some considerations of the method of apply invocation. Finally, the difference between the invocation method and call invocation mode is pointed out.
Today's topic is to talk about here, thank you for your cheer.

Brother Tai Propitiate, about arguments, your idea is the same as the great god----Chat the Apply and call in JS

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.