79200640

Date: 2024-11-18 16:15:13
Score: 1
Natty:
Report link

Indeed, you cannot assign anything to this. I have no idea what is your understanding of this, but it makes no sense. I'll try to give you an idea by modifying your code. First, I renamed your class, because you may need to separate things at the same time, an element and its wrapper:

class ElementWrapper {

    constructor(name, className, attributes, innerText) {
        this.element = document.createElement(name);
        this.element.setAttribute("class", className);
        if (attributes) {
            Object.keys(attributes).forEach(attr => {
                this.element.setAttribute(attr, attributes[attr]);
            });
        };
        if (innerText) this.element.innerText = innerText;
    };

    addAttribute(name, value) {
        this.element.setAttribute(name, value);
        return this.element;
    }

} // class ElementWrapper

You did not have any class members, but I've introduced two: a property element and a method addAttribute.

The usage example:

const wrapper = new ElementWrapper(/*  */);
const rawElement = wrapper.element;
const sameElementNamed =
    wrapper.addAttribute("name", "my-button");
const anotherWrapper = new ElementWrapper(/*  */);
anotherWrapper.addAttribute("name", "my-section");

Here, new shows that you call ElementWrapper not as a regular function (you can do it if you want), but as a constructor.

The call returns some reference for you, and this is a reference to the created instance of ElementWrapper. You use this reference for accessing the instance. When you call wrapper.addAttribute(/* ... */), you pass the instance wrapper as an implicit argument to addAttribute. The class's method needs this reference to know which of the possible ElementWrapper instances should be used to access the instance. How the code of addAttribute can know what is this, wrapper or anotherWrapper? Because you pass one or another instance reference using a name before the dot.

Reasons:
  • Blacklisted phrase (1): what is your
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Sergey A Kryukov