我在Javascript中对OOP全新,并试图创建一个OO测验应用程序。我在Javascript中发现了一篇关于OOP的精彩文章,但是在这个例子中,这个人只是亲自制作实例,如下所示:
/ A User
firstUser = new User("Richard", "Richard@examnple.com");
firstUser.changeEmail("RichardB@examnple.com");
firstUser.saveScore(15);
firstUser.saveScore(10);
但是在我的应用程序中,我当然希望用户输入他的名字,以html格式发送电子邮件,当他点击按钮时,我希望创建该特定用户的新实例。现在我该怎么做到这一点?我知道我需要在按钮上设置事件监听器,构造函数参数应该等于用户输入的输入值。这是我到目前为止所提供的,但不知道我是不是走向正确的方向:
function User (theName, theEmail) {
/*this.name = {
var theName = document.getElementsByTagName("input").val();
},*/
this.name = function () {
theName = document.getElementById("user_name").val();
}
this.email = function () {
theEmail = document.getElementById("user_email").val();
}
//this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
User.prototype = {
constructor: User,
saveScore: function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd);
},
showNameAndScore: function () {
var Score = this.quizScores.length > 0 ? this.quizScores.join(",") : "No scores yet";
return this.name + "score is " + Score;
},
changeEmail: function (newEmail) {
this.email = newEmail;
return "new email saved:" + this.email;
}
}
function clickBtn () {
var btn = document.getElementById("button");
btn.addEventListener("click", function () {
var user1 = new User (this.name, this.email);
});
}
尽管如此,我觉得这不是这样做的方法。任何帮助将不胜感激,谢谢。
答案 0 :(得分:1)
示例:
const name = document.getElementById('name')
const surname = document.getElementById('surname')
const age = document.getElementById('age')
const button = document.getElementById('submit')
const users = [];
class User {
constructor(n, s, a) {
this.name = n || 'John';
this.surname = s || 'Doe';
this.age = a || '18'
}
}
button.addEventListener('click', function() {
const user = new User(name.value, surname.value, age.value);
users.push(user);
console.log(JSON.stringify(users, null, 2))
});

Name <input type="text" id="name">
Surname <input type="text" id="surname">
Age <input type="number" id="age">
<hr>
<button id="submit">Submit</button>
&#13;
在onClick上创建了新的User
对象,并且所有用户都存储在users
数组中。如果输入值为空 - 则设置默认值。