1. 程式人生 > 其它 >53.js物件-建構函式

53.js物件-建構函式

<body>
<div id="test1"></div>
<div id="test2"></div>
</body>
<script>

//建立物件
var user1 = new User();
user1.showInfo("test1");

var user2 = new User(null, "韓梅梅", "hanmeimei", 2, new Date(1995, 5-1, 1));
user2.showInfo("test2");

/* 宣告建構函式 */
//user物件的建構函式
function User(id, userName, password, gender, birthday) {
this.id = id || "";
this.userName = userName || "佚名";
this.password = password || "0000";
this.gender = gender || 0;
this.birthday = birthday || "";
this.showInfo = function (idName) {

var msg = "<hr>"
+ "使用者資訊如下:<br>"
+ "id: " + this.id + "<br>"
+ "使用者名稱: " + this.userName + "<br>"
+ "密碼: " + this.password + "<br>"
+ "性別: " + this.genderName() + "<br>"
+ "生日: " + this.birthday + "<br>"
+ "年齡: " + this.age() + "<hr>";

document.getElementById(idName).innerHTML = msg;
}
this.genderName = function () {
if (this.gender == 1) return "男";
if (this.gender == 2) return "女";
return "保密";
}
this.age = function () {

//計算過程略...

return 18;
}
}

</script>