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:
I need some clarity because I keep getting errors even when I do those rules lol. Can someone explain this
to me please? Thanks
What code have you written that you are getting errors?
Here is my JS and HTML so you can try yourself.
JS
class Timer {
constructor(durationInput, startButton, pauseButton) {
this.durationInput = durationInput;
this.startButton = startButton;
this.pauseButton = pauseButton;
this.startButton.addEventListener('click', this.start.bind(this));
}
start() {
this.importantMethodCall()
}
}
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>
<html>
<head></head>
<body>
<input id="duration" />
<button id="start">Start</button>
<button id="pause">Pause</button>
<script src="timer2.js"></script>
</body>
</html>
1 Like
danpetroski:
class Timer {
constructor(durationInput, startButton, pauseButton) {
this.durationInput = durationInput;
this.startButton = startButton;
this.pauseButton = pauseButton;
this.startButton.addEventListener('click', this.start.bind(this));
}
start() {
this.importantMethodCall()
}
}
This code represents the class
. If you want to have importantMethodCall
be a method of this class, then it needs to be nested inside the {
and }
of the Timer
class definition.
AHh okay. So the start()
method needs to be put in the closing }
above it? I see.
No, the importantMethodCall
method needs to be moved above the last }
above the importantMethodCall
method.
Yeah, lol. That’s my bad. That’s what I meant to say.