Combination of JavaScript Inheritance
1, using the Call method
Definition: Invokes one method of an object, replacing the current object with another object.
<! DOCTYPE html>Humans.call (this,name);//borrowing the properties of a constructorThis.age=age; }man.prototype=new humans ();//Inherit humans functionvar man1=new man ("that Dish", 23); Man1.clothing.push ("Pian"); alert (man1.clothing); //output: "Jacket", "nylon jacket", "Sport socks", "Pian"var man2=new man ("Horse Whoop", 34); alert (man2.clothing); //output: "Jacket", "nylon jacket", "Sport socks"</script> </body>
2,apply method
Definition: A method of applying an object that replaces the current object with another object.
<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", 21, "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 //Student Class I did not assign a value to the name and age attribute Ah, why do they have the values 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
3,
under what circumstances use apply, under what circumstances use call
In the case of an object parameter, if the argument is in the form of an array, such as the argument arguments is passed in the apply example, the parameter is an array type, and the list of arguments is consistent when the person is called (that is, The first two bits of the parameter list for person and student are consistent) and can be applied if my person's argument list is (Age,name), and Student's argument list is (Name,age,grade), This can be done with call, that is, directly specify the position of the corresponding value of the parameter list (Person.call (This,age,name,grade));
The difficulty of JavaScript begins---Use the call method and the Apply method