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

209
Visualizações
Can I access "this" from a class property?

I'm trying to call this inside the onClick function which is inside the object, but I'm getting undefined in the console. Why is this happening?

Panel.tsx:

import * as React from 'react';

import PanelInterface from './Panel.Interface';
import Config from "../../Config";

const Panel: React.FC<PanelInterface> = (props) =>
{
    const config = new Config({
        panel : {
            onClick: function() {
                console.log(this);
            }
        }
    }).get();

    return (
        <div {...config.panel}/>
    );
};

export default Panel;

Config.ts:

export default class Config
{
    private readonly configuration: any;

    constructor(configuration: Object)
    {
        this.configuration = configuration;
    }

    public get(): any
    {
        return this.configuration;
    }
}

Console output:

undefined
undefined

Edit: Usage arrow functions has no effect. Also undefined in output.

Edit: The question was closed as a duplicate, although it is not. I managed to solve the problem by changing in Panel.Config:

export default new Config({
    panel : {
        className : css.panel,
        onClick: () => {
            console.log(this);
        }
    }
});

to:

const config = new Config({
    panel : {
        className : css.panel,
        onClick: () => {
            console.log(config);
        }
    }
});

export default config;

So in onClick instead of this I can use config.

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