Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
Call class method within D3 method

I have a JS class where I'm using D3. I've created a button element that I need to execute a class function upon being pressed. What is the proper way to do this?

class MyClass{
...
   foo(bar){
      d3.select("button").on("click",function(){ this.print(bar) });
   }

   print(text){
      console.log(text);
   }
}

As far as I know, going within the scope of function(){..} loses the binding of this and the instance of MyClass, because it claims that this.print() is not a function.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

To do it you can save your class instance inside a variable

in my sample

let _this = this;

And use this new variable in your d3 function

class MyClass{
...
   foo(bar){
      let _this = this;
      d3.select("button").on("click",function(){ _this.print(bar) });
   }

   print(text){
      console.log(text);
   }
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use an arrow function to keep the reference to the instance's this context. In the words of the docs:

In arrow functions, this retains the value of the enclosing lexical context's this.

Your code could thus be rewritten as

d3.select("button").on("click", () => this.print(bar));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda