document.addEventListener("DOMContentLoaded", () => {
document.querySelector('start'),addEventListener('click', () =>{
var car = new Car('Audi');
document.addEventListener('keyup', e=>{
car.printName();
})
})
})
class Car{
constructor(name){
this.name = name
}
printName(){
console.log(this.name)
}
}
I am trying to create a simple game using JavaScript OOP. After the DOM loads and the player hits the 'start' button, a new Car object is created by passing the object's name property. For simplicity, the only method in the class for now is 'printName' which prints.
The problem is the previous object remains in the memory even though the game should reset whenever the player hits start button, since I have created a brand new object.
Notice, in the above code, whenever a player hits 'start' button two times and presses any key, the 'printName' method gets invoked for both new and old object. How can I tackle this problem?