The cognition of Call () and apply ()

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)

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:

<script type="Text/javascript" >

/* Define 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 ("Qian", "first grade");

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.

</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. ["Qian", "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.

The cognition of Call () and 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.