I have a class that runs a function cloneButtons during construction. The cloneButtons function takes an array oldButtons and returns an array newButtons of the same exact elements. My problem is that I'm encountering weird behavior when I try to deconstruct the array. Whenever I use this to make a class assignment, things just stop working.
I'm new to JS but can't find any documentation about limitations of using this and why it wouldn't work when destructuring the return value of a function.
Here are some examples of what works and what doesn't. The following code works as intended: the elements in cloneButtons deconstructs without issue.
constructor () {
const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
const [attackBtn, healBtn, specialBtn] = Utils.cloneButtons(oldButtons)
attackBtn.addEventListener('click', this.attackHandler.bind(this))
// this works perfectly
}
However, if I try to assign the array elements using this while destructuring at any step in the process I get a variety of errors, all stemming from the fact that whatever variable has this remains undefined. This throws an initialization error:
constructor () {
const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
[this.attackBtn, this.healBtn, this.specialBtn] = Utils.cloneButtons(oldButtons)
this.attackBtn.addEventListener('click', this.attackHandler.bind(this))
// cannot access oldButtons before initialization
}
Another method that does not work:
constructor () {
const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
this.newButtons = Utils.cloneButtons(oldButtons)
[this.attackBtn, this.healBtn, this.specialBtn] = this.newButtons
this.attackBtn.addEventListener('click', this.attackHandler.bind(this))
// this.attackBtn is undefined
}
To help id what going wrong here's another scenario that works perfectly, which involves no destructuring:
constructor () {
const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
this.newButtons = Utils.cloneButtons(oldButtons)
this.newButtons[0].addEventListener('click', this.attackHandler.bind(this))
//works but does not use destructuring
}
Additionally, I cannot even run this.oldButtons = document.querySelectorAll(#id) as this for some reason returns undefined. What am I missing here?!