javascript物件導向繼承的三種方法:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
//基類
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);};
}
//子類
function ManPerson()
{
this.Name="ManPerson";
this.Sex="Man";
this.Age="20"
Person.apply(this);//執行該語句時會調用Person中的構造器,先前賦值的ManPerson,Man,20就失去作用了,所以這句話
//要放在this.Name="ManPerson";之前才能即繼承Person的方法,又不會覆蓋我們的賦值操作。
}
//第一種方法
function first(){
var p=new Person();
alert("Name:"+p.Name+" Sex:"+p.Sex+" Age:"+p.Age);//執行結果為Name:Person Sex:NONE Age:?
p.SayName();//執行結果Person
var mp=new ManPerson();
alert("Name:"+mp.Name+" Sex:"+mp.Sex+" Age:"+mp.Age);//apply在賦值後結果為:Name:Person Sex:NONE Age:?
//在賦值前結果為:Name:ManPerson Sex:Man Age:20
mp.SaySex();//執行結果Man
//可以看到ManPerson很好的繼承了Person
}
//第二種方法
function second(){
for(pro in Person)
{
ManPerson[pro]=Person[pro];
}
var p=new Person();
alert("Name:"+p.Name+" Sex:"+p.Sex+" Age:"+p.Age);//執行結果為Name:Person Sex:NONE Age:?
p.SayName();//執行結果Person
var mp=new ManPerson();
alert("Name:"+mp.Name+" Sex:"+mp.Sex+" Age:"+mp.Age);//執行結果為Name:Person Sex:NONE Age:?
mp.SaySex();//執行結果NONE
mp.Name="ManPerson";
mp.SayName();//執行結果:ManPerson
//可以看到ManPerson繼承了Person的SayName
}
function third(){
//第三種方法
ManPerson.prototype=Person.prototype;
var mmp=new ManPerson();
mmp.SayName();//執行結果:Person
mmp.Name="ManPerson";
mmp.SayName();//執行結果:ManPerson
//ManPerson繼承了Person的方法
}
</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>
原創文章,轉載請註明出處!
All CopyRight Reserved !
首頁:http://jingtao.cnblogs.com
QQ:307073463
Email:jingtaodeemail@qq.com
MSN:sunjingtao@live.com