JavaScript functions apply and call

Source: Internet
Author: User

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

Function.apply (Obj,args) method can receive two 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: Same as apply, except that the argument list is not the same.

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

1. Apply Example:

[JavaScript]View Plaincopy
  1. <script type="Text/javascript" >
  2. / * Define a human * /
  3. function Person (name,age)
  4. {
  5. This.name=name;
  6. This.age=age;
  7. }
  8. / * Define a Student class * /
  9. Functionstudent (Name,age,grade)
  10. {
  11. Person.apply (this,arguments);
  12. This.grade=grade;
  13. }
  14. //Create a student class
  15. var student=new Student ("Zhangsan", "first grade");
  16. //Test
  17. Alert ("name:" +student.name+"\ n" +"Age:" +student.age+"\ n" +"Grade:" +student.grade);
  18. //You can see the test results Name:zhangsan age:21 Grade: First grade
  19. //Student Class I did not assign a value to the name and age attribute Ah, why the value of these two properties, this is the magic of apply.
  20. </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 execute the contents of the person class, in the person class inside the existence of this.name and other statements, so that the property is created into the student object

2. Call Example

In the Studen function, you can modify the apply to read as follows:

Person.call (This,name,age);

That's OK.

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

In the case of an object parameter, if the argument is in the form of an array, such as the parameter arguments is passed in the apply example, the parameter is an array type, and the list of parameters is consistent when the person is called ( That is, the first two bits of the parameter list of the person and student are consistent) can be applied, if my person's parameter list is such (Age,name), and Student's argument list is (Name,age,grade), This can be done with call, that is, directly specify the position of the corresponding value of the parameter list (Person.call (This,age,name,grade));

4. Some other clever uses of apply

The attentive person may have noticed that when I invoke the Apply method, the first argument is the object (this), the second argument is an array collection, and when you call person, it is not an array, But why would he give me an array? I can still parse the array into one parameter , which is a clever use of apply, you can convert an array by default to a parameter list ([PARAM1,PARAM2,PARAM3] to param1, PARAM2,PARAM3) This, if we use the program to implement each item of the array as a list of parameters, it may take a while, with the use of this feature, so there are the following efficient methods:

A) Math.max can be implemented to get the largest item in the array

Because the Math.max parameter does not support Math.max ([PARAM1,PARAM2]), which is the array

But it supports Math.max (param1,param2,param3 ...), so you can solve the Var max=math.max.apply (Null,array) According to the characteristics of the 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 it to a method)

This block in the call when the first parameter gave 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 on the line. So it passed directly a null past

b) Math.min can be implemented to get the smallest item in the array

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

c) Array.prototype.push can implement two array merging

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

[JavaScript]View Plaincopy
    1. vararr1=New Array ("1","2","3");
    2. vararr2=New Array ("4","5","6");
    3. Array.prototype.push.apply (ARR1,ARR2);

It is also possible to understand that arr1 invokes the push method, which is a set of parameters that can be assembled into a parameter list by using apply.

Under what circumstances, you can use a special usage like math.min and so on:

In general, the target function requires only n argument lists, not the form of an array ([param1[,param2[,... [, Paramn]]] ), you can solve this problem skillfully by apply way!

1. Each function contains two non-inherited methods: Apply () and call ().
2. They are used in the same way, and are called functions in a specific scope.
3, the receiving parameters are different, apply () receives two parameters, one is the function run scope (this), and the other is a parameter array.
The first parameter of the call () method is the same as the Apply () method, but the arguments passed to the function must be enumerated.
Example 1:

Copy CodeThe code is as follows:
Window.firstname = "Diz";
Window.lastname = "song";
var myObject = {firstName: "My", LastName: "Object"};
function Helloname () {
Console.log ("Hello" + This.firstname + "" + This.lastname, "Glad to meet you!");
}
Helloname.call (window); Huo. Call (this);
Helloname.call (MyObject);


The result of the operation is:
Hello Diz song glad to meet you!
Hello my Object glad to meet you!
Example 2:

Copy CodeThe code is as follows:
function sum (NUM1, num2) {
return NUM1 + num2;
}
Console.log (Sum.call (window, 10, 10)); 20
Console.log (Sum.apply (window,[10,20)); 30


Analysis: in Example 1, we found that the real use of apply () and call () is to be able to expand the scope of the function to run, if we want to implement the traditional method, see the following code:

Copy CodeThe code is as follows:
Window.firstname = "Diz";
Window.lastname = "song";
var myObject = {firstName: "My", LastName: "Object"};
function Helloname () {
Console.log ("Hello" + This.firstname + "" + This.lastname, "Glad to meet you!");
}
Helloname (); Hello Diz song glad to meet you!
Myobject.helloname = Helloname;
Myobject.helloname (); Hello my Object glad to meet you!


See Accents's code, we find that to make the Helloname () function scoped on the object MyObject, we need to dynamically create the Helloname property of the MyObject, which points to the Helloname () function as a pointer, so that When we call Myobject.helloname (), the This variable inside the function points to MYOBJECCT, and you can call the internal other public properties of the object.
By analyzing example 2, we can see the real use of the call () and apply () functions, and in the actual project, it is necessary to deal with the actual flexibility!
A small problem: take a look at the case of the this variable when defining a function in a function

Copy CodeThe code is as follows:
function Temp1 () {
Console.log (this); Object {}
function Temp2 () {
Console.log (this); Window
}
Temp2 ();
}
var Obj = {};
Temp1.call (OBJ); Run the result see above green comment!!!!


The execution results are the same as the following:

Copy CodeThe code is as follows:
function Temp1 () {
Console.log (this);
Temp2 ();
}
function Temp2 () {
Console.log (this);
}
var Obj = {};
Temp1.call (OBJ);


4. Bind () method
Browsers that support this approach are ie9+, firefox4+, safari5.1+, opera12+, and Chrome. It is a method that belongs to ECMAScript5. See examples directly:

Copy CodeThe code is as follows:
Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
alert (This.color);
}
var osaycolor = Saycolor.bind (o);
Osaycolor (); Blue

5. Summary:

At first I do not understand the apply very much, the last to see a few times, I have to knock a few times the code, only to understand the middle of the truth, so, no matter what to do, as long as they are willing to move the brain, willing to strike code, such a technology will be mastered ...

There are, for example, the fourth part of the content, ingenious solution to the real problem, this is certainly not a beginner can think of the solution (this is not my own thinking), do not have 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!

JavaScript functions apply and call

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.