Rules of "this" keyword in JS

So I’m hitting a point in my Udemy course where this was and is being used to bind etc. The instructor said there are two main “rules” to using it.

Here is the “rule” from the slides:

Screenshot 2023-03-13 14.10.28

I need some clarity because I keep getting errors even when I do those rules lol. Can someone explain this to me please? Thanks

Here is my JS and HTML so you can try yourself.


class Timer {
  constructor(durationInput, startButton, pauseButton) {
    this.durationInput = durationInput;
    this.startButton = startButton;
    this.pauseButton = pauseButton;

    this.startButton.addEventListener('click', this.start.bind(this));

  start() {

importantMethodCall() {
  console.log('The thing was called!')

const durationInput = document.querySelector('#duration');
const startButton = document.querySelector('#start');
const pauseButton = document.querySelector('#pause');

const timer = new Timer(durationInput, startButton, pauseButton);

HTML (linked for JS file)

<!DOCTYPE html>
    <input id="duration" />
    <button id="start">Start</button>
    <button id="pause">Pause</button>
    <script src="timer2.js"></script>
1 Like

AHh okay. So the start() method needs to be put in the closing } above it? I see.

Yeah, lol. That’s my bad. That’s what I meant to say.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.