Three ways to JavaScript object-oriented inheritance:
<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);
}
Sub Class
function Manperson ()
{
This. Name= "Manperson";
This. Sex= "Man";
This. Age= "20"
Person.apply (this); The constructor in person is invoked when the statement is executed, and the previously assigned manperson,man,20 is out of effect, so the sentence
To put in this. Name= "Manperson", before you can inherit the person's method without overwriting our assignment operation.
}
The first of these methods
function A () {
var p=new person ();
Alert ("Name:" +p.name+ "Sex:" +p.sex+ "Age:" +p.age);//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);//apply The result is: Name:person Sex:none Age:?
The result before assignment is: Name:manperson Sex:man age:20
Mp. Saysex ()//Execution Result man
You can see that Manperson inherits the person very well.
}
The second method
function second () {
For (Pro on person)
{
Manperson[pro]=person[pro];
}
var p=new person ();
Alert ("Name:" +p.name+ "Sex:" +p.sex+ "Age:" +p.age);//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);//execution result is Name:person Sex:none age:?
Mp. Saysex ()//execution Result None
Mp. Name= "Manperson";
Mp. Sayname ()//execution Result: Manperson
You can see Manperson inherits the person's Sayname
}
function third () {
The third method
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's method
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<button value= "FirstMethod" onclick= "a", >firstmethod</button><br/>
<button validationgroup= "Secondmethod" onclick= "second ()" >secondmethod
</button><br/>
<button value= "Thirdmethod" onclick= "third ()" >ThirdMethod</button>
</div>
</form>
</body>