js 创建对象例子
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><script>function login() {alert(this.username + " - login");}function CreateUser(username, password) {
// var user = new Object;this.username = username;this.password = password;this.show = function() {alert("username = " + this.username + " / password = " + this.password);}this.changePassword = function(password) {this.password = password;}this.login = login;
// user.prototype.resetPassword = function () {
// this.password = "123456";
// }
// return user;
// 如果将user的声明取消掉,直接用this,就会自动创建对象,并且最后自动返回对象。}var u;var u2 = new CreateUser("tom","coco");function testCreate(username, password) {u = new CreateUser(username, password);}function testChangePassword(password) {u.changePassword(password);}function testShow() {u.show();u2.show();}function testLogin() {u.login();u2.login();}function testResetPassword() {alert("暂时停用");u.resetPassword();u2.resetPassword();}</script></head><body>创建user对象<br /><button type="button" οnclick="testCreate(prompt('input username'),prompt('input password'))">testCreate</button><br /><br /><br />更改密码<br /><button type="button" οnclick="testChangePassword(prompt('input password'))">testChangePassword</button><br /><br /><br />显示user信息<br /><button type="button" οnclick="testShow()">testShow</button><br /><br /><br />user登陆<br /><button type="button" οnclick="testLogin()">testLogin</button><br /><br /><br />user重设密码123456(prototype注释)<br /><button type="button" οnclick="testResetPassword()">resetPassword</button></body>
</html>