mardi 23 mars 2021

Is right to extend javascript Elements?

I'd like to create a particular logic for a div element, and create it with a constructor, but i need to use many Element properties, so was wondering if a solution like this

class MyElement extends HTMLDivElement {
    constructor(father) {
        super();
        if (father === undefined)
           father = document.body;
        father.appendChild(this);
        this.className = this.constructor.name;
    }
}
.
.
.
// Main.js
customElements.define('my-element', MyElement, { extends: 'div' });

or a solution like this

class MyElement extends jQuery.fn.init {
    constructor(father) {
        if (father === undefined)
            father = document.body;
        super("<div>");
        this.$wrapper = null;
        this.__proto__ = jQuery.extend(true, this.__proto__, this.__proto__.__proto__)
        this.appendTo(father);
        this.attr("class", this.constructor.name);
    }
}

could be reasonable, or "standard", and what could be pro and cons for these solutions, for example, if there could be problems of compatibility, or could be considered a bad practice




Aucun commentaire:

Enregistrer un commentaire