1

Code #1

What is the practical difference between

document.getElementById("clearbutton").addEventListener("click", storage.clearStorage);

vs.

Code #2

document.getElementById("clearbutton").addEventListener("click", function() {
  storage.clearStorage();
});

?

I'm practicing JS and HTML and found this weird interaction with addEventListener. storage is an instance of a class that has a method clearStorage. storage.clearStorage() is suppose to clear the localStorage value of user. When I click on a button with the id "clearbutton", code #1 does not clear localStorage but when I use code #2, it does clear localStorage. That this means to me is that the storage.clearStorage() function is working properly but maybe something is wrong with addEventListener. Otherwise, I have no idea why code#1 doesn't work as I thought both codes are equivalent. If this is important, this is how I implemented clearStorage().

class StorageHandler {
   constructor () {
     this.storage = {"taco": 1}
   }
   clearStorage() {
      console.log("clearStorage runned.")
      this.storage = {}
      console.log(this.storage)
      window.localStorage.setItem("user", JSON.stringify({}));

    }
}
var storage = new StorageHandler;

When I run storage.storage in the console of chrome after clicking the clearbutton, using code #1, it shows me {"taco": 1}. But when I use code #2, storage.storage is equal to {}.

Thanks for reading this!

The Shagod
  • 51
  • 1
  • 5

0 Answers0