Js Apply Method Specific explanation

Source: Internet
Author: User

Js Apply Method Specific explanation

I started to see JavaScript function apply and call, very vague, see also do not understand, recently on the Internet to see some articles on the Apply method and call some examples of demonstration, finally is a bit of a look at, here I do such as the following notes, I hope to share with you. If there is anything wrong or the words do not understand where the reader would like to make a lot of comments in order to improve together.

Mainly I want to solve a few problems:

1. Where are the differences between apply and call?

2. Under what circumstances use apply, and under what circumstances call

3. Other clever ways to use apply (generally under what circumstances you can use apply)

I first look at the definition of apply and call from the Internet, and then use the Demo sample to explain the meaning of the two methods and how to use them.

Apply: Methods can hijack another object's method, inheriting another object's properties.

Function.apply (Obj,args) method can receive two of the parameters
OBJ: This object will replace the This object in the function class
Args: This is an array, which is passed as a parameter to function (args-->arguments)

Call: As with apply, it's just a different list.

Function.call (obj,[param1[,param2[,... [, Paramn]]])
OBJ: This object will replace the This object in the function class
Params: This is a list of references

1. Apply Demo Sample:

<script type= "Text/javascript" >/* defines a human */function person (name,age) {this.name=name;this.age=age;} /* Define a Student class */functionstudent (Name,age,grade) {person.apply (this,arguments); this.grade=grade;} Create a student class Var student=new student ("Zhangsan", 21, "first grade");//Test Alert ("Name:" +student.name+ "\ n" + "Age: +student.age+" \ n "+" Grade: "+student.grade");//You can see the test results Name:zhangsan age:21  Grade: First grade//student Class I didn't assign a value to the name and age attribute Ah, why are the values of these two properties exist again? , this is the magic of apply .</script>


Analysis: Person.apply (this,arguments);

This: In the creation of the object at this time represents the student

Arguments: is an array, i.e. ["Zhangsan", "21", "first grade"];

That is, the popular point is: Use student to run the contents of this class, in person this class exists this.name and so on, such as the statement, so that the property is created into the student object inside

2. Call Demo sample

In the Studen function, you can change the apply to such as the following:

Person.call (This,name,age);

That's OK.

3. Under what circumstances use apply, and under what circumstances call

In the case of a given object, assuming that the form of the parameter is an array, for example, the arguments is passed in the example of the Apply demo, which is an array type, and the list of the parameters is consistent when the person is called ( That is, the person and the student list of the first two of the table is the same) can be used to apply, assuming that my person's list is this (Age,name), and Student's list is (Name,age,grade), This can be achieved with call, that is, directly specify the corresponding value of the list of parameters (Person.call (This,age,name,grade));

4. Some other clever ways to use apply

The attentive person may have noticed that when I invoke the Apply method, the first parameter is the object (this), the second parameter is an array collection, and when you call person, he does not need an array. But why did he give me an array? I can still parse the array into a single parameter, which is an ingenious use of apply to convert an array by default to a list of parameters ([PARAM1,PARAM2,PARAM3] to param1 , PARAM2,PARAM3) This hypothesis allows us to use the program to implement each item of the array to replace the list of parameters, it may take a while, with the help of this feature of apply, so there is the following efficient method:

A) Math.max is able to achieve the largest item in the array

Because Math.max ([param1,param2]) is not supported in the Math.max parameter, the array

However, it supports Math.max (param1,param2,param3 ...), so it can solve Var max=math.max.apply (Null,array) According to the characteristics of just apply. This makes it easy to get the largest item in an array (apply will change a number assembly to a parameter by passing a number of parameters to the method )

This block in the call when the first parameter to give a null, this is because there is no object to call this method, I just need to use this method to help me to calculate the return of the results can be. So directly passed a null past

b) Math.min is able to achieve the smallest item in the array

The same and Max is a thought var min=math.min.apply (Null,array);

c) Array.prototype.push enables two arrays to be merged

The same push method does not provide an array of push, but it provides push (Param1,param,... paramn) So the same can be used to replace this array with apply, namely:

Vararr1=new Array ("1", "2", "3"); Vararr2=new Array ("4", "5", "6"); Array.prototype.push.apply (ARR1,ARR2);

It is also possible to understand that arr1 invokes the push method, and the number of references is set by using apply to replace the assembly with the list of parameters.

Under what circumstances, you can use special use methods like Math.min and so on:

In general, the objective function requires only n list of parameters, not the form of an array ([param1[,param2[,... [, Paramn]]] ), can solve the problem skillfully by the way of apply!

5. Summary:

At the beginning I did not understand the application very much, and finally read a few times, I have to knock a few times the code, only to clear the middle of the truth, so, no matter what to do, just to own the brain, willing to write programs, such a technology will be mastered ...

For example, the fourth part of the content, cleverly overcome the real problem, this is certainly not a beginning to learn the person can think of the solution (this is not my own thinking), there is not a certain understanding of programming will not think of this, or a sentence, more accumulation, more study, The most important thing is to improve your ability and understanding of programming ideas!

Most of the content is from:

Http://www.cnblogs.com/xiaohongwu/archive/2011/06/15/2081237.html

The middle is my specific understanding of it ...

I am also a JS freshman, assuming that the blog where the writing is not a problem or this is not good place, I hope the predecessors more generous enlighten, thank you

Js Apply Method Specific explanation

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.