Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda