Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
¿Cómo podría crear un contenedor de elementos en Javascript?

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 element

Entonces, 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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda