0

I have a problem with creating a new Object in the constructor My Aim is to take the user input and from that create a new object and push into an array using the constructor. The problem is that when I try to fill the new input to create a new object it just replaced the old one with undefined values. MY code :

let Book = document.querySelector("#one");
let Author = document.querySelector("#two");
let Year = document.querySelector("#three");
let Btn = document.querySelector("button");
Btn.addEventListener("click", () => {
 Book = Book.value;
 Author = Author.value;
 Year = Year.value;
 let myLibrary = [];
 function newBook(name, author, year) {
 this.name = name;
 this.author = author;
 this.year = year;
 }
 function addBookToLibrary(book, author, year) {
 const Books = new newBook(book, author, year);
 myLibrary.push(Books);
 }
 addBookToLibrary(Book, Author, Year);
 console.log(myLibrary);
});
Mat
208k41 gold badges409 silver badges423 bronze badges
asked Aug 21, 2021 at 7:13

1 Answer 1

1
 let Book = document.querySelector("#one");
let Author = document.querySelector("#two");
let Year = document.querySelector("#three");
let Btn = document.querySelector("button");
let myLibrary = [];
Btn.addEventListener("click", () => {
 function newBook(name, author, year) {
 this.name = name;
 this.author = author;
 this.year = year;
 }
 function addBookToLibrary(book, author, year) {
 const Books = new newBook(book, author, year);
 myLibrary.push(Books);
 }
 addBookToLibrary(Book.value, Author.value, Year.value);
 console.log(myLibrary);
});

There are two mistakes in above code:

  1. You are using local state of let myLibrary = []; which will be created on every click. It should be moved to a higher level so that on every click the value added can be preserved.

  2. You are using same name of variables inside your function, which are overriding the Dom reference.

answered Aug 21, 2021 at 7:30
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.