首页 > 解决方案 > 扩展 javascript 元素是否正确?

问题描述

我想为 div 元素创建一个特定的逻辑,并使用构造函数创建它,但我需要使用许多 Element 属性,所以想知道是否有这样的解决方案

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' });

或这样的解决方案

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);
    }
}

可能是合理的或“标准的”,以及这些解决方案的优缺点,例如,如果可能存在兼容性问题,或者可能被视为不好的做法

标签: javascripthtmljqueryoopweb

解决方案


推荐阅读