0

I am using classes in JavaScript and having a problem.

  • I define a parent class and child class
  • I then instantiate an object based on these
  • I then call a method from the child class, with a click event, but this method cannot seem to read the properties I am trying to access.

Here is my JavaScript Code

class Box {
  constructor(boxId) {
    this.boxElement = document.getElementById(boxId)
  }
}

class SampleBox extends Box {
  constructor(boxId) {
    super(boxId)
    this.sampleText = this.boxElement.value
    this.wordCount = 0
    this.textConfirmed = false
  }

  refreshSampleText() {
    console.log(this.wordCount)
    this.sampleText = this.boxElement.value
  }
}

sampleBoxObject = new SampleBox('display-area')

confirmBtn = document.getElementById('confirm-button')
confirmBtn.addEventListener('click', 
sampleBoxObject.refreshSampleText)

My aim is to read the contents of boxElement and assign it to a property called sampleText but this is not happening. (As you can see from the Box Class, boxElement is a dom object - in this case its a text area.)

The console.log in the method is only there to see if I was able to read any of the properties created by the constructor, but it can't, as it is coming back undefined.

I know that the object instance is being created and the variables are being set using the constructor because I have checked in this in the console.

(As an aside, I am not trying to update the html element. I am trying to get information from it so that I can manipulate that information after. The word 'refresh' in the method name might be misleading.)

It is baffling me and I would be grateful for any assistance.

Luke Peavey
  • 3,777
  • 22
  • 24
  • A possible dupe target (but the explanations aren't that good or missing completely...): [Class methods as event handlers in JavaScript?](https://stackoverflow.com/questions/229080/class-methods-as-event-handlers-in-javascript) – Andreas Sep 07 '20 at 09:17
  • you have to bind a context confirmBtn.addEventListener('click', sampleBoxObject.refreshSampleText.bind(sampleBoxObject)); – Dezigo Sep 07 '20 at 09:37

0 Answers0