arw89
arw89

Reputation: 107

'this' keyword within a function used on an HTML element

See this codepen

or the code snippet below

How can I get the button to log to the console when it is clicked? I am trying to learn how to use this in JavaScript. Thanks

const button = document.getElementById("leet");

function LeetSpeaker (elem) {
  return {
    listenClick () {
      const self = this
      elem.addEventListener('click', function () {
        self.speakLeet()
      })
    },
    speakLeet() { console.log(`1337 15 4W350M3`) }
  }
}
button {
  background-color: #b666d2;
  border: none;
  width: 100px;
  height: 30px;
  font-size: 1em;
  border-radius: 10px;
  font-family: Verdana;
}
button:hover {
  background-color: rebeccapurple;
}
<button id="leet" onclick="LeetSpeaker(button)">Click</button>

Upvotes: 0

Views: 109

Answers (1)

baao
baao

Reputation: 73241

The problem isn't this in your code. Get rid of the inline javascript, execute LeetSpeaker(button).listenClick() in your js code and it works. To do it better, use an arrow function and then just this.speakLeet()

const button = document.getElementById("leet");
LeetSpeaker(button).listenClick();

function LeetSpeaker(elem) {
  return {
    listenClick() {
      const self = this
      elem.addEventListener('click', function() {
        self.speakLeet()
      })
    },
    speakLeet() {
      console.log(`1337 15 4W350M3`)
    }
  }
}
button {
  background-color: #b666d2;
  border: none;
  width: 100px;
  height: 30px;
  font-size: 1em;
  border-radius: 10px;
  font-family: Verdana;
}

button:hover {
  background-color: rebeccapurple;
}
<button id="leet">Click</button>

Or nicer, with an arrow function

const button = document.getElementById("leet");
LeetSpeaker(button).listenClick();

function LeetSpeaker(elem) {
  return {
    listenClick() {
      elem.addEventListener('click', () => {
        this.speakLeet()
      })
    },
    speakLeet() {
      console.log(`1337 15 4W350M3`)
    }
  }
}
button {
  background-color: #b666d2;
  border: none;
  width: 100px;
  height: 30px;
  font-size: 1em;
  border-radius: 10px;
  font-family: Verdana;
}

button:hover {
  background-color: rebeccapurple;
}
<button id="leet">Click</button>

Upvotes: 1

Related Questions