Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
Tener las sutilezas del prototipo extendido sin extender realmente el prototipo

Lo que estoy tratando de hacer es tener una interfaz en la que pueda envolver un elemento en una instancia que tenga un prototipo extendido, algo así como.

 const wrappedButton = new WrappedElem(document.getElementById('some-button')) // we have access to our custom added method: console.log(`I am the ${wrappedButton.siblingIndex()}th button`) // but we still have access to the original methods wrappedButton.addEventListener('click', function(e){ console.log('I clicked on', e.target) // right here we won't have access to siblingIndex, because the prototype of the element itself was not changed. })

Puedo extender el prototipo original así

 HTMLElement.prototype.siblingIndex = function() { if(this.parentNode == null) { return -1 } return Array.prototype.indexOf.call(this.parentNode.children, this) }

Pero extender el prototipo es una mala práctica y un mal desempeño.

Entonces, ¿es posible hacer algo como esto?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Al usar un Proxy, podemos agregar un nuevo método sin cambios en el prototipo:

 const siblingIndex = () => {} const handler = { get(target, property) { if(property === 'siblingIndex') { return siblingIndex; } return target[property]; } } const proxyButton = new Proxy(button, handler); // we can also call the siblingIndex function proxyButton.siblingIndex(); // we can access the properties of the underlying object proxyButton.tagName;

Sin embargo, e.target no devolverá el proxy sino el objeto original, pero puede usar proxyButton en lugar de e.target

si lo desea, también puede anular el método addEventListener para devolver la versión de proxy en su lugar cuando se llama a la devolución de llamada

about 4 years ago · Juan Pablo Isaza Relatório

0

Esto es lo que parece funcionar bien. Muchas gracias a Lk77.

 var wrappedElMethods = { siblingIndex() { if(this.parentNode == null) { return -1 } return Array.prototype.indexOf.call(this.parentNode.children, this) } } function wrappedEl(el) { return proxyInherit(el, wrappedElMethods) } function proxyInherit(item, overwrites) { const handler = { get(target, property) { let value const overwriteVal = overwrites[property] if(overwriteVal != undefined) { value = overwriteVal } else { value = target[property] } if(value instanceof Function) { return value.bind(item) } return value }, set(target, property, value) { target[property] = value } } return new Proxy(item, handler) } // Usage: var button = wrappedEl(e.target) button.onclick = function() { console.log(button.siblingIndex()) }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda