Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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); 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!