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

252
Visualizações
How to export a prototype method?

How to export a prototype method?

I created a prototype method:

Array.prototype.remove = function(elementToRemove: any): void {
    var __idx = this.indexOf(elementToRemove);
    if (__idx >= 0) {
        this.splice(__idx, 1);
    } else {
        throw new Error(`Cannot find element ${elementToRemove}`)
    }
}

and I want to export it and use in another file. But I don't know how to add export to it:

both

export Array.prototype.remove = function(elementToRemove: any)

and

Array.prototype.remove = export function(elementToRemove: any)

doesn't work, I received 'Expression expected' Error. So how can I export it?

ps: I'm not using nodejs, I'm using web frontend in chrome with HTML and CSS.

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

0

The fundamental issue is that your code performs a side-effect - it adds something to Array.prototype.

One option is to export a function that, when called, adds the function to the prototype:

export const addRemoveToPrototype = () => {
  Array.prototype.remove = function( // ...

and then consumers can use it by doing

import { addRemoveToPrototype } from './addRemoveToPrototype';
addRemoveToPrototype();

Another option is to simply run that code at the top level of the module:

Array.prototype.remove = function(elementToRemove: any): void {

and then consumers can just import the module, but not do anything with it:

import './addRemoveToPrototype';

That said, I'd really recommend not mutating built-in objects - it makes the code fragile and more easily breakable, especially when other scripts run in the same environment.

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