0

I have been stuck on this for a good hour now and i know its something so simple but cant wrap my head around it

Soooo both variables that i have set in the constructor are undefined outside of the constructor when calling them.

This is a js file eventually being used for a search component on a shopify site. Thanks in advance!

See the code below:

class PredictiveSearch extends HTMLElement {
  
  constructor(){
    super();
    
    //Set elements
    this.searchBtn = this.querySelector('#search-btn');
    this.searchContainer = this.querySelector('#main-search_wrapper');
    
    // Set event listeners
    this.searchBtn.addEventListener("click", this.openSearch);
  }
  
  // Open search overlay
  openSearch(){
    console.log(this.searchContainer);
    this.searchContainer.style.display = "block";
  }
  
}

customElements.define('predictive-search', PredictiveSearch); 
  • 1
    Does this answer your question? [How to access the correct \`this\` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Ivar Apr 20 '22 at 11:07
  • 1
    Thank you @Ivar !! Yes! calling 'this' depends on where it is called from. So binding the openSearch function to this fixed my problem. Thanks again! – Zach Said Apr 20 '22 at 11:17

2 Answers2

1

Your HTML probably hasn't been loaded when openSearch() is called. Check if the elements have been loaded first before calling the function.

loading = setInterval(() => {
    if (document.getElementById("main-search_wrapper")) {
        openSearch();
        clearInterval(loading);
    }
}, 100);

If this doesn't work, try bind openSearch() to this in the constructor to make sure this is correct.

function constructor() {
    ...
    this.searchContainer = this.querySelector('#main-search_wrapper');

    const openSearch = (() => {
       console.log(this.searchContainer);
       this.searchContainer.style.display = "block";              
    }).bind(this);
}
0

I believe that this is because this doesn't refer to the class/instance of the class when it's inside the constructor() function. I think it refers to the function itself.

  • 1
    No. The `this` depends on how the function is being called. Whether it is used inside a constructor is irrelevant. See [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). Or more specifically for this case [How to access the correct `this` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Ivar Apr 20 '22 at 11:22
  • I don't want to ruin the fun, but your answer _does_ have a downvote. It just also happens to have an upvote. – Ivar Apr 20 '22 at 11:25
  • Haha oh well, at least I've learned something :) At least I know why it was downvoted. – JeanRemyDuboc Apr 20 '22 at 11:25