0

I'm trying to dynamically create elements via a class constructor and use a method to grab the object data of the element clicked and no matter what I try I'm unable to call my getInfo() method. The method works perfectly fine when it's called outside of the class as object.getInfo()

class Shape {
    constructor(name, color) {
        this._name = name;
        this._color = color;
        this.getInfo = function() {
            return `${this._name} ${this._color}`
        }
    }

createShape() {
        const element = document.createElement('div');
        document.querySelector('.shape-container').appendChild(element);
        element.style.cssText += 'background-color:' + this._color;

        shapeContainer.addEventListener('click', function (e) {
            const target = e.target;
            if (target.matches('div')) {
                output.innerHTML = this.getInfo();
            }
        });

Console will output Uncaught TypeError: this.getInfo is not a function

I am also having issues with the event buttons outputting extra results for each existing element (three elements = 3 outputs when I click any of them)

Sorry if my question doesn't make sense, I'm new to this.

Apricosma
  • 7
  • 2
  • Use an arrow function... `shapeContainer.addEventListener("click", (e) => { ... })` – Phil Nov 23 '22 at 02:29
  • 1
    FYI you should probably define `getInfo()` as a method just like `createShape()`. There's no need to declare it in the constructor – Phil Nov 23 '22 at 02:31

0 Answers0