Three methods of JavaScript Object-oriented Inheritance:
< HTML xmlns = " Http://www.w3.org/1999/xhtml " >
< Head runat = " Server " >
< Title > Untitled page </ Title >
< Script Language = " Javascript " Type = " Text/JavaScript " >
// Base Class
Function person ()
{
This . Name = " Person " ;
This . Sex = " None " ;
This . Age = " ? " ;
This . Sayname = Function () {Alert (This. Name );} ;
This . Saysex = Function () {Alert (This. Sex );} ;
This . Sayage = Function () {Alert (This. Age );} ;
}
// Subclass
Function manperson ()
{
This . Name = " Manperson " ;
This . Sex = " Man " ;
This . Age = " 20 "
Person. Apply ( This ); // When executing this statement, the constructor in person will be called. The manperson, man, and 20 previously assigned values will become useless.
// This. Name = "manperson"; can inherit the person method without overwriting our value assignment operation.
}
// Method 1
Function first () {
VaR P = New Person ();
Alert ( " Name: " + P. Name + " Sex: " + P. Sex + " Age: " + P. Age ); // The execution result is name: person sex: None age :?
P. sayname (); // Execution result person
VaR MP = New Manperson ();
Alert ( " Name: " + MP. Name + " Sex: " + MP. Sex + " Age: " + MP. Age ); // The result of applying assignment is: Name: person sex: None age :?
// The result is: Name: manperson sex: man age: 20.
MP. saysex (); // Execution result man
// We can see that manperson inherits the person
}
// Method 2
Function second () {
For (Pro In Person)
{
Manperson [pro]=Person [pro];
}
VaR P = New Person ();
Alert ( " Name: " + P. Name + " Sex: " + P. Sex + " Age: " + P. Age ); // The execution result is name: person sex: None age :?
P. sayname (); // Execution result person
VaR MP = New Manperson ();
Alert ( " Name: " + MP. Name + " Sex: " + MP. Sex + " Age: " + MP. Age ); // The execution result is name: person sex: None age :?
MP. saysex (); // Execution result none
MP. Name = " Manperson " ;
MP. sayname (); // Execution result: manperson
// Manperson inherits the sayname of person.
}
Function third () {
// Method 3
Manperson. Prototype = Person. Prototype;
VaR MMP = New Manperson ();
MMP. sayname (); // Execution result: person
MMP. Name = " Manperson " ;
MMP. sayname (); // Execution result: manperson
// Manperson inherits the person method.
}
</ Script >
</ Head >
< Body >
< Form ID = " Form1 " Runat = " Server " >
< Div >
< Button Value = " Firstmethod " Onclick = " First () " > Firstmethod </ Button > < BR />
< Button validationgroup = " Secondmethod " Onclick = " Second () " > Secondmethod
</ Button > < BR />
< Button Value = " Thirdmethod " Onclick = " Third () " > Thirdmethod </ Button >
</ Div >
</ Form >
</ Body >
</ Html >
Original article. For more information, see the source!
All copyright reserved!
Home: http://jingtao.cnblogs.com
QQ: 307073463
Email: jingtaodeemail@qq.com
MSN: sunjingtao@live.com