Object disguise (Construction Inheritance Method)What is object disguise? We may call constructor inheritance easier to understand. As the name suggests, it is to use constructors to play inheritance. In fact, the constructor of the parent class is treated as a common method and put into the constructor of the subclass for execution. In this way, when constructing an object, of course, the subclass object can construct the parent class method!
Or the example above,CodeAs follows:
Function animal ()
{
This. Run = function () {alert ("I can run ");};
}
Function people (name)
{
// Here the constructor of the parent class is passed in, and then the constructor of the parent class is executed. At this time, the methods in the parent class can be used.
This. Father = animal;
This. Father ();
// Remember to delete it. Otherwise, when the subclass is added to a method with the same name as the parent class, it is changed to the parent class.
Delete this. Father;
This. Name = Name;
This. Say = function () {alert ("My name is" + this. Name );}
}
Function girl (name, age)
{
This. Father = people;
This. Father (name );
Delete this. Father;
This. Age = age;
This. Introduce = function () {alert ("My name is" + this. Name + ". I am" + this. Age );};
}
In this way, an inheritance chain is implemented, and the test is as follows:
VaR A = new animal ();
A. Run ();
VaR P = new people ("windking ");
P. Run ();
P. Say ();
VaR G = New Girl ("Xuan", 22 );
G. Run ();
G. Say ();
G. Introduce ();
The result is as follows:
A.
B.
C.
D.
E.
F.
Test successful!
Let's summarize the key of this Code, specifying the parent class, declaring the parent class object, and then deleting the temporary variable. Do you think it is a little troublesome? At least I think so. Once I forget Delete, I still have to bear the risk of the parent class being modified. To solve this problem, we use call and apply to improve it!
Next, let's look at the code and the above example (to make it easier for everyone to understand and change the requirement, animal has a name ):
Function animal (name)
{
This. Run = function () {alert ("I can run ");};
}
Function people (name)
{
// Use the call method to implement inheritance
This. Father = animal;
This. Father. Call (this, name );
This. Name = Name;
This. sayname = function () {alert ("My name is" + this. Name ;);};
}
Function girl (name, age)
{
// Use the apply method to implement inheritance
This. Father = people;
This. Father. Apply (this, new array (name ));
This. Age = age;
This. Introduce = function () {alert ("My name is" + this. Name + ". I am" + this. Age );};
}
With the same test code, we found that the test was as successful.
If you are a newbie, you may be confused about the two sections of code. What is call and what is apply? Well, I joined a series of additional journals in this topic. If you don't know about this, read my article: Call and apply.