1

Let's assume I've defined a custom element like this:

class ArticleElement extends HTMLElement {
  constructor() {
    super();
    console.log(this); //the node we are (re)defining
    this.innerHTML = `
      <article>
        <h2>${this.getAttribute("title")}</h2>
        <p>${this.innerHTML}</p>
      </article>`;
  }
}

customElements.define("custom-article", ArticleElement);

My question is - how does this become the node we are (re)defining? Is this possible to be done in pure JavaScript without using native methods? Because if we execute the constructor with new, this points to the newly created object. I was trying to implement the define method like this:

function define(tag, CustomElement) {
  const elementsCollection = document.getElementsByTagName(tag);
  Object.keys(elementsCollection).forEach((index) => {
    Object.setPrototypeOf(elementsCollection[index], CustomElement.prototype);
    elementsCollection[index].constructor();
  });
}

define("custom-article", ArticleElement);

But then remembered that the constructor of a class cannot be executed without new.

Here's my html file (if it even matters):

...
<custom-article title="Today is the day!">
   Today is a great day to go out and breathe some fresh air!
</custom-article>
...
  • `this` is a dynamic variable and what it actually points to is determined by mostly the call site. [this here](https://stackoverflow.com/a/3127440/9898651) is probably the best write up i've ever seen about `this`. – Adam H Mar 01 '23 at 18:06

0 Answers0