Zach Said
Zach Said

Reputation: 1

Javascript variable undefined well referencing outside of constructor

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); 

Upvotes: 0

Views: 437

Answers (2)

JeffreytheCoder
JeffreytheCoder

Reputation: 84

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);
}

Upvotes: 1

JeanRemyDuboc
JeanRemyDuboc

Reputation: 83

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.

Upvotes: 0

Related Questions