Con fines puramente educativos y de curiosidad, estoy tratando de crear un objeto contenedor de elementos que me permita agregar mis propias propiedades y métodos a un elemento. El comportamiento que estoy tratando de simular es básicamente este:
// get a button element to wrap const button = document.querySelector('button'); // some function that wraps new properties/methods around a given element function wrap(element) { this.customName = 'John'; this.customAge = 100; this.printName = function() { console.log(this.customName); } // ... // ...somehow inherit element fields... // ... } // wrap the button element const customElement = new wrap(button); // custom behavior: console.log(customElement.customAge) // output => 100 customElement.printName() // output => 'John' // legacy behavior console.log(customElement.clientHeight) // output => client height customElement.remove() // => should still call 'remove' on the elementEntonces, aquí debería poder agregar mis propios métodos/propiedades pero seguir accediendo a los campos originales normalmente. ¿Es esto posible?
Estoy usando una función constructora aquí como ejemplo solo para demostrar el comportamiento previsto, pero en realidad no sé si esto sería relevante para la solución. Soy nuevo en Javascript y he investigado mucho sobre prototipos y clases, pero todavía estoy confundido sobre qué enfoque tomaría aquí.
Editar: como señaló Brad en los comentarios, también probé esta implementación usando clases:
class MyButton extends HTMLButtonElement { constructor() { super(); this.customName = 'John'; this.customAge = 100; } printName() { console.log(this.customName); } } const myBtn = new MyButton(); Pero esto resultó en el error: Uncaught TypeError: Illegal constructor
No he probado esto, pero tal vez algo como esto:
// get a button element to wrap const button = document.querySelector('button'); // some function that wraps new properties/methods around a given element function wrap(element) { Object.defineProperties(element, { customName: {value:"John"}, customAge: {value:100}, printName:{value: () => console.log(element.customName)} }) return element } // wrap the button element const customElement = wrap(button); // custom behavior: console.log(customElement.customAge) // output => 100 customElement.printName() // output => 'John' // legacy behavior console.log(customElement.clientHeight) // output => client height customElement.remove() // => should still call 'remove' on the element <button>Hello world!</button>Otro método que podría usarse es envolver el elemento en proxy() Esto permitirá devolver datos personalizados si la propiedad no existe y enviar notificaciones cuando las propiedades cambien:
const customElement = function (element, properties = {}) { this.element = element; this.customName = 'John'; this.customAge = 100; this.printName = function() { console.log(this.customName); } //override default properties for(let i in properties) { if (i in element) element[i] = properties[i]; else this[i] = properties[i]; } return new Proxy(this, { get(target, prop) { if (prop in target.element) //is property exists in element? { if (target.element[prop] instanceof Function) return target.element[prop].bind(target.element); return target.element[prop]; } else if (prop in target) //is property exists in our object? return target[prop]; else return "unknown property"; //unknown property }, set(target, prop, value, thisProxy) { const oldValue = thisProxy[prop]; if (prop in target.element) target.element[prop] = value; else target[prop] = value; // send notification target.element.dispatchEvent(new CustomEvent("propertyChanged", { detail: { prop, oldValue, value } })); } }); } const button = new customElement(document.createElement("button"), {customName: "Not John"}); button.addEventListener("propertyChanged", e => { console.log("property changed", e.detail); }); button.printName(); console.log("age:", button.customAge); console.log("height:", button.clientHeight); console.log("blah:", button.blah); button.blah = "ok"; console.log("blah:", button.blah);