A brief introduction to the detailed usage of appy and call in JS

Source: Internet
Author: User

Apply and call two Laosheng saying goes method, the use of some of the details of the process is still a great difference, the specific use of the case can be reviewed in detail in the following example.

Differences and explanations: the use of call () and apply () in JS

1. Doubts about call () and apply ():
    • What is the difference between apply and call?
    • Under what circumstances use apply, under what circumstances use call
    • Other clever uses of apply (generally under what circumstances you can use apply)

2. Syntax and parametric analysis:

Both apply and call can inherit the methods and properties of another object;
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

3. The call () and apply () examples show:

/* Define a person class */function person (name,age) {      this.name=name;      This.age=age;}  /* Define a Student class *  /function Student (name,age,grade) {     //person.apply (this,arguments);//Features: This refers to the Student object, Only 2 parameters are received, arguments is an implicit class array object, used to receive incoming parameters,      person.call (this,name,age);//Features: This refers to the student object, can receive any number of parameters      This.grade=grade;  }  var student =new student ("Zhangsan", 22, "sophomore");//Method student () is also an instance of object//test  alert ("Name:" +student.name+ "\ n") + "Age:" +student.age+ "\ n" + "Grade:" +student.grade);//I don't assign a value to the name and the age attribute in the student class, why is there the value of these two properties, this is the magic of apply.


Name:zhangsanage:22grade: "Second Grade"

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

4, under what circumstances with apply, under what circumstances with call

When using apply: in the case of an object parameter, if the argument is in the form of an array, such as the arguments parameter is passed in the Apply example, this parameter is an array type.

When using call: If my person's argument list is (Age,name), and Student's argument list is (Name,age,grade), it can be done with call, That is, directly specifying the position of the corresponding value of the parameter list (Person.call (This,age,name,grade));

5. Some other clever usages 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 an array into one parameter.

This is a clever use of apply, you can convert an array by default to a parameter list [PARAM1,PARAM2,PARAM3] to param1,param2,param3 If you let us 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:


6. Other important uses of call:Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]] Description: The calling method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj. if the Thisobj parameter is not provided, then the Global object is used as the thisobj. 6.1. Replace the B object directly with the A object method

Analysis: The meaning of this example is to replace sub,add.call (sub,3,1) = = Add (3,1) with add, so the result is: alert (4); Note: The function in JS is actually an object, and the function name is a reference to a function object.

   6.2. The method of executing a object directly with a B object
Analysis: Note that call means to put the C1 method on the C2, the original C2 is no Shownam () method, is now C1 the Shownam () method put to C2 to execute, so this.name should be class2, the result of execution is: alert (" Class2 "); You can let a object execute the method of the B object. 6.3, can use call to achieve inheritance
Analysis: that is, I have a method or property that I don't have, and with call inheritance, I have your methods and properties that you can do about it.。 So Class2 inherit Class1, Class1.call (this) means to use the Class1 object instead of the This object, then Class2 all the properties and methods Class1, C2 object can directly call Class1 method to and attributes, the result of execution is: alert ("CC");

A brief introduction to the detailed usage of appy and call in JS

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.