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

165
Visualizações
How to overload the Set Class

How would I overload the Set.prototype.add method, for example I'm trying to do:

// allow overloading the Set().method function by passing multiple arguments
Set.prototype.add = function(x) {
    for (let x of arguments) {
        super.add(x); // doesn't Set act like a class?
    }
    return this;
}
let s = new Set([1,2,3]);
s.add(4,5,6);
console.log("Set: ", s);
// 'super' keyword unexpected here

Or do I need to alias it like this so I can call the parent via Function.call/apply, such as:

Set.prototype.addMultiple = function(x) {
    for (let x of arguments) {
        Set.prototype.add.call(this, x);
    }
    return this;
}
let s = new Set([1,2,3]);
s.addMultiple(4,5,6);
console.log("Set: {" + Array.from(s) + "}");

Or, what about just aliasing the original method, is that considered ok? (or does Set.prototype._add = Set.prototype.add; have unintended side effects?):

Set.prototype._add = Set.prototype.add;
Set.prototype.add = function(x) {
    for (let x of arguments) {
        Set.prototype._add.call(this, x);
    }
    return this;
}

let s = new Set([1,2,3]);
s.add(4,5,6);
console.log(`Set: {${Array.from(s)}}`);

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

0

You don't need all of these fancy features; just this:

Set.prototype.addMultiple = function(x) {
    for (let x of arguments) {
        this.add(x);
    }
    return this;
}

While we're at it, let's use const instead in the loop:

for (const x of arguments) {

And also arguments? That's some 2010 code. Nowadays we use spread/variadic arguments:

Set.prototype.addMultiple = function (...args) {
    for (const x of args) { ... }
     
    // rest omitted
}

Keep in mind that extending/modifying native prototypes is generally frowned upon, so you're better off extending the class instead.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can subclass the Set with something like the following:

class _Set extends Set {
    add(_) { 
        Array.from(arguments).map((x) => super.add(x));
        return this;
    }
}

let s = new _Set([1,2,3]);
s.add(4,5,6);
console.log(`Set: ${Array.from(s)}`);

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