Apply () and call ()

Source: Internet
Author: User

apply () and call ()Are all part of a function.prototype approach. is implemented within the JavaScript engine because it belongs to Function.prototype, so every instance of a function object, that is, each method has a call, the Apply property. Since as a property of a method, The use of them is, of course, for the method. These two methods are easy to confuse, because they work just the same way.

the same point: two methods produce The effect is exactly the same

Different points: Methods pass different parameters

Use is to call a function in a specific scope, which is actually equal to the value of the this object in the body of the function.

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)
    • function method is applied to obj?
    • Call, the role of apply is to borrow someone else's way to invoke, just like calling their own.
The call () method is the same as the Apply () method, where the difference is only in the way that the parameter is accepted, the second parameter is a list of parameters, and when you use Call (), the parameters passed must be listed individually. Apply () instance:
1 functionPerson (name,age) {2            This. Name =name;3            This. Age;4 }5 functionStudent (name,age,grade) {6Person.apply ( This. arguments);7            This. grade =grade;8 }9 varStudent =NewStudent ("123 ', 12," third grade "));TenAlert ("Name:" +student.name+ "Age:" +student.age+ "Grade:"+student.grade); OneName:123 Age:12 Grade: Third grade

  Analysis: person.apply (this,arguments);this: When creating this object, it represents the student.arguments:["123 ', 12," third grade "];In other words: Using student to execute the contents of the person in this class, there are statements such as this.name in the person class, so that the attributes are created into the student object. Example of call ():Person.call (this,name,age);  The choice between the two depends on the most convenient way to pass parameters to the function. If it is intended to pass directly to the arguments object, or an array that is first accepted in the function, it would be more convenient to use apply (), or call (); some applications: 1.math.max:
1 var value = [1,2,3,4,5,6,7,8,9]; 2 3 var max = Math.max.apply (math.value);

 use the Math object as the first parameter of apply () to set the value of this correctly, and then you can use any array as the second argument.  (because the Math.max parameter does not support Math.max ([PARAM1,PARAM2]) is an 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 application just now, so it is easy to get the largest item in an array (apply will change a number assembly to a parameter to a parameter to pass to the 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 directly passed a null past)   2.array.prototype.pushThe 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:
1 var New Array ("1", "2", "3"); 2 3 var New Array ("4", "5", "6"); 4 5  6 7 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. 3.array.prototype.slice.call (arguments)You can convert an object with the length property to an array. (with array conversion general function):
1 varToArray =function(s) {2           Try{3                      returnArray.prototype.slice.call (s);4}Catch(e) {5                                        vararr = [];6                                         for(vari = 0, len = s.length; i< len;i++)7Arr[i] =S[i];(arr.push (s[i]))8                                        returnarr;9                              }Ten}

  the real purpose of apply () and call () is to expand the scope in which the function is to run
1Window.color = "Red";2 varo = {color: ' Blue '};3 4 functionSaycolor () {5Alert This. color);6 }7 8Saycolor ();//Red9Saycolor.call ( This);//RedTenSaycolor.call (window);//Red OneSaycolor.call (o);//Blue

the biggest benefit of using call () or apply () to extend from the scope is that the object does not need to have any coupling with the method.   bind () This method creates an instance of a function whose this value is bound to the value passed to the bind () function.
1Window.color = "Red";2 varo = {color: ' Blue '};3 4 functionSaycolor () {5Alert This. color);6 }7 8Saycolor ();//Red9Saycolor.call ( This);//RedTenSaycolor.call (window);//Red OneSaycolor.call (o);//Blue

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.