背景:这是一段“类”设计模式案例:设计2个控制器,一个用来操作网页中的登陆表单,一个用来与服务器进行验证。案例中设计了一个Controller父类,并关联了2个子类LoginController(操作登陆表单),AuthController(与服务器进行验证)。
问题:具体有几段代码不理解其中的含义,已在代码中标注指出,请高人帮忙详细解析下。感谢!
//父类
function Controller() {
this.errors = [];
}
Controller.prototype.showDialog = function (title, msg) {
// 给用户显示标题和消息
};
Controller.prototype.success = function (msg) {
this.showDiglog("Success", msg);
};
Controller.prototype.failure = function (err) {
this.errors.push(err);
this.showDialog("Error", err);
};
//子类 LoginController
function LoginController() {
Controller.call(this);
}
//把子类关联到父类
LoginController.prototype = Object.create(Controller.prototype);
LoginController.prototype.getUser = function () {
return document.getElementById("login_username").value;
};
LoginController.prototype.getPassward = function () {
return document.getElementById("login_password").value;
};
LoginController.prototype.validateEntry = function (user, pw) {
var user = user || this.getUser();
var pw = pw || this.getPassward();
if (!(user && pw)) {
return this.failure("Please enter a username & password!");
} else if (pw.length < 5) {
return this.failure("Password must be 5+ characters!");
}
return true;
};
LoginController.prototype.failure = function (err) {
Controller.prototype.failure.call(this, "Login invalid: " + err);
};
// 子类AuthController
function AuthController(login) {
Controller.call(this);
this.login = login;
}
//把子类关联到父类
AuthController.prototype = Object.create(Controller.prototype);
console.log(AuthController);
AuthController.prototype.server = function (url, data) {
return $.ajax({
url: url,
data: data,
});
};
AuthController.prototype.checkAuth = function () {
//如何理解this.login.??? this.login 不是function
var user = this.login.getUser();
//问题同上
var pw = this.login.getPassward();
//问题同上
if (this.login.validateEntry(user, pw)) {
this.server("/check-auth", { user: user, pw: pw })
.then(this.success.bind(this))
.fail(this.failure.bind(this));
}
};
AuthController.prototype.success = function () {
Controller.prototype.success.call(this, "Authienticated!");
};
AuthController.prototype.failure = function () {
Controller.prototype.failure.call(this, "Auth Failed:" + err);
};
var auth = new AuthController();
auth.checkAuth(
// 这段代码含义?
new LoginController()
);