Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Cómo sobrecargar la clase Set

¿Cómo sobrecargaría el método Set.prototype.add , por ejemplo, estoy tratando de hacer:

 // 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

¿O necesito un alias así para poder llamar al padre a través Function.call/apply , como:

 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) + "}");

O, ¿qué hay de simplemente crear un alias del método original, se considera correcto? (¿o Set.prototype._add = Set.prototype.add; tiene efectos secundarios no deseados?):

 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 answers
Answer question

0

No necesita todas estas características sofisticadas; solo this :

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

Mientras estamos en eso, usemos const en su lugar en el ciclo:

 for (const x of arguments) {

¿Y también arguments ? Eso es un código de 2010. Hoy en día usamos argumentos de dispersión/variádicos:

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

Tenga en cuenta que extender/modificar prototipos nativos generalmente está mal visto, por lo que es mejor que extienda la clase.

about 4 years ago · Juan Pablo Isaza Report

0

Puede subclasificar el Set con algo como lo siguiente:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!