當然也可以把showInformation函數放入到School函數裏面.
但是這樣做程序的結構不夠好啊
<html>
<head>
<title>Sample!!</title>
<mce:script type="text/javascript"><!--
//直接初始化對象
var ZGKJDX={name:"學",
address:"安",
grade:"高等學府",
number:"13400",
information:showInformation
};
//定義對象的方法
function showInformation()
{
var msg="";
msg="自定義對象實例:/n";
msg+="/n機構名稱 : "+this.name+" /n";
msg+="所在地址 : "+this.address +"/n";
msg+="教育層次 : "+this.grade +" /n";
msg+="在校人數 : "+this.number
window.alert(msg);
}
// --></mce:script>
</head>
<body>
<form action="">
<input type="button" value="調試對象按鈕" οnclick="ZGKJDX.information()" />
</form>
</body>
</html>
直接化的方法來初始化對象。
<mce:script type="text/javascript"><!--
//對象的構造函數
function School(iName,iAddress,iGrade,iNumber)
{
this.name=iName;
this.address=iAddress;
this.grade=iGrade;
this.number=iNumber;
this.information=showInformation;
}
//定義對象的方法
function showInformation()
{
var msg="";
msg="通過原型給對象添加新屬性和新方法:/n/n"
msg+="原始屬性:/n";
msg+=" 機構名稱 : "+this.name+" /n";
msg+=" 所在地址 : "+this.address +"/n";
msg+=" 教育層次 : "+this.grade +" /n";
msg+=" 在校人數 : "+this.number+" /n/n";
msg+="新屬性:/n";
msg+=" 佔地面積 : "+this.addAttributeOfArea+" /n";
msg+="新方法:/n";
msg+=" 方法返回 : "+this.addMethod+"/n";
window.alert(msg);
}
function MyMethod()
{
var AddMsg="New Method Of Object!";
return AddMsg;
}
//生成對象的實例
var ZGKJDX=new School("中國學","安","高等學府","13400");
School.prototype.addAttributeOfArea="3000";
School.prototype.addMethod=MyMethod();
// --></mce:script>
動態添加方法和屬性.
內嵌對象
也可以在外面定義
var SchoolData={
code:"0123-456-789",
Tel:"0551-1234567",
Fax:"0551-7654321"
};
之後通過
var ZGKJDX={
name:"學",
address:"安",
grade:"高等學府",
number:"13400",
//嵌套對象SchoolData
data:SchoolData,
information:showInformation
};
引入來創建對象。