0

I'm totally new to OOP in Javascript and trying to create a OO quiz app. I came across a great article on OOP in Javascript, but in the examples the guy just makes the instances by hand, like this:

/ A User ​
firstUser = new User("Richard", "[email protected]"); 
firstUser.changeEmail("[email protected]");
firstUser.saveScore(15);
firstUser.saveScore(10); 

But in my application, of course I want the user to type in his name, email in the html form and when he clicks the button, I want the new instance for that specific user to be created. Now how can I achieve this? I know that I need to set up event listener on the button and the constructor arguments should be equal to the input value that the user will type in. This is what I came with so far, but have no idea if I'm going the right direction:

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);
});
}

Still, I feel like this is not the way to do this. Any help would be appreciated, thanks.

1 Answer 1

1

Example:

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>

New User object is created onClick, and all users are stored inside users array. If input values are empty - default values are set.

Sign up to request clarification or add additional context in comments.

6 Comments

Wow, this was really that simple, I don't know why I did overthink this. Thanks. But now I start wondering if there is any point to use OOP for this type of simple app functionality. I mean one of the reason is to encapsulate and structure the code, but at the end it looks kinda loosely anyway, no? Would you really code the quiz app this way that you showed me? And regarding class and const keywords, is it ES6 syntax?
This is es6 syntax, right. Well, there are many possible ways to code the same thing, so you choose whatever you like the most. My approach is not better than yours, it's just an answer to your question on how can you can dynamically create similar objects. If you create a user just once, you can just validate values beforehand and use a literal object in place, or validate using es6 Proxy for example. Whatever you choose, if it works than it's fine )
can I use var instead of const in this situation if I'm using es5 syntax? I don't want to dive into es6 before I learn es5 properly.
Never mind, I got it working with var. I know there is huge difference between const and var and I'm not sure of it, but as long as it is working, I think I'm good. My current code: var user = []; var theName = document.getElementById("user_name"); var theEmail = document.getElementById("user_email"); function User (theName, theEmail) { this.name = theName; this.email = theEmail;
I don't see anything bad with it. If it works it's ok.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.