Apply & Call

Source: Internet
Author: User

One. Significance

Function.apply (Obj,args)

Obj replaces function in this object

Args passed as a parameter to function

Two. Instance

1. obj in place of the This object in function

1     function f () {2          alert (this. Y); 3     }4      var obj = {x:1,y:2}; 5      F.call (obj);         // 3

2. API Application

Math.max (Param1,param2,param3 ...): Implementation gets the largest item in the array

Problem: Max does not support array parameters

Solution: According to the characteristics of apply to solve

var max=math.max.apply (null, array)

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. Undefine is an undefined object, NULL is a defined object, but without an instance, it can be understood that NULL is the defined of obj.

3. Inheritance

1 /*Define a human*/2     functionPerson (Name,age)3     {4          This. name=name;5          This. age=Age ;6     }7     /*define a student class*/8 functionstudent (Name,age,grade)9     {TenPerson.apply ( This, arguments); One          This. grade=grade; A     } -     //Create a Student class -     varStudent=NewStudent ("Qian", 21, "first Grade")); the     //Test -Alert ("Name:" +student.name+ "\ n" + "Age:" +student.age+ "\ n" + "Grade:" +student.grade); -     //You can see the test results Name:qian age:21 Grade: First grade -     //I did not assign a value to the name and age attribute in the student class, why is there the value of these two properties, this is the magic of apply.

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.