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);
});
1 Answer 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:
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.You are using same name of variables inside your function, which are overriding the Dom reference.
Comments
Explore related questions
See similar questions with these tags.