我是 Javascript 中的 OOP 新手。我正在学习继承。下面是我的代码。我在这里没有使用任何原型和创建函数,但仍然设法继承。我知道这不是正确的做法。但是为了实现我的目标,我应该如何重写代码以利用实际的继承。
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script type="text/javascript" >
// Validation Class
var Validation = function() {
this.isEmpty = function(val) {
if (val == "")
return true;
}
}
// Ajax Class
var Ajax = function() {
this.url = "";
this.data = "";
this.send = function(val) {
alert("Data send to " + this.url + " succeessfully");
}
}
// Form Class
var LoginForm = function(action, username, password) {
Validation.call(this);
Ajax.call(this);
this.action = action;
this.username = username;
this.password = password;
}
var loginObj = new LoginForm("domain/server", "john", '123456');
loginObj.url = loginObj.action;
loginObj.isEmpty(loginObj.username);
loginObj.isEmpty(loginObj.password);
loginObj.data = {username: loginObj.username, password: loginObj.password};
loginObj.send();
</script>
</head>
<body>
</body>
</html>
编辑:但是当我这样尝试时,它会抛出错误。
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script type="text/javascript" >
// Validation Class
var Validation = function() {
this.isEmpty = function(val) {
if (val == "")
return true;
}
}
// Ajax Class
var Ajax = function() {
this.url = "";
this.data = "";
this.send = function(val) {
alert("Data of "+this.data.username+" send to " + this.url + " succeessfully");
}
}
// Inheritance
Ajax.prototype = Object.create(Validation);
var LoginForm = "";
LoginForm.prototype = Object.create(Ajax);
// Form Class
LoginForm = function(action, username, password) {
this.action = action;
this.username = username;
this.password = password;
}
var loginObj = new LoginForm("domain/server", "john", '123456');
loginObj.url = loginObj.action;
loginObj.isEmpty(loginObj.username);
loginObj.isEmpty(loginObj.password);
loginObj.data = {username: loginObj.username, password: loginObj.password};
loginObj.send();
var loginObj2 = new LoginForm("domain/server", "JAMES", '123456');
loginObj2.url = loginObj2.action;
loginObj2.isEmpty(loginObj2.username);
loginObj2.isEmpty(loginObj2.password);
loginObj2.data = {username: loginObj2.username, password: loginObj2.password};
loginObj2.send();
</script>
</head>
<body>
</body>
</html>