- 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 ()