0

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.

  • What do you *want* it to be? A reference to the `Config` object? To `config.panel`? Something else? – T.J. Crowder Feb 02 '22 at 07:23
  • I thought it would config.panel. – dakovic323 Feb 02 '22 at 07:27
  • @dakovic323 - No, `this` inside a function in an object literal doesn't refer to the object being created ([more here](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers)). In this particular case you could just use `config.panel` instead of `this`. Otherwise, you'd have to [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) it after the fact or similar. – T.J. Crowder Feb 02 '22 at 07:39

0 Answers0