Atribute of object appearing undefined even after having been initialized before JS

Viewed 30

I have been trying to use an attribute from an Object that I've used before and the second time I call it in another function it comes as undefined. I have checked with console.log its values and appears assigned. Does anyone knows whats I'm getting wrong ?

class Tab {
    thing: Thing;
    thingHistory: ThingHisotry;
    response: HttpResponse;
    request: HttpRequest;
    status: "sending" | "waiting";
    element: Element;

    constructor() {

        // Tab Element
        const tabElement = document.createElement('li');
        tabElement.classList.add('tagElement');

        // Tab Element Wrapper
        const tabElementWrapper = document.createElement('div');
        tabElementWrapper.classList.add('playNameDiv');
        tabElementWrapper.innerHTML = `
            <button>
                <span class="material-symbols-outlined">play_circle</span>
            </button>
            <p>${(this.thing) ? this.thing.name : 'Thing 1'}</p>
        `;

        // Tab Close Button
        const tabCloseBtn = document.createElement('button');
        tabCloseBtn.setAttribute('type', 'button');
        tabCloseBtn.classList.add('closeTagButton');
        tabCloseBtn.innerHTML = `<span class="material-symbols-outlined">close</span>`;
        tabCloseBtn.addEventListener('click', this.remove);

        tabElement.appendChild(tabElementWrapper);
        tabElement.appendChild(tabCloseBtn);

        this.element = tabElement;   -----> This atribute
        console.log(this.element) 
    }

    remove() {
        console.log(this.element);

        this.element.remove();   -------> Appears undefined the second time
    }

}

enter image description here

1 Answers

You lost this reference

tabCloseBtn.addEventListener('click', this.remove.bind(this));
Related