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

234
Views
Agregar un método al prototipo de una variable de cadena

Esperado: cuando se crea una variable mediante createGreetable , debe tener una propiedad adicional de greet establecida por greetable(text) . Los métodos string habituales aún deberían poder llamarse en esta variable.

Lo que probé:

 const greetablePrototype = { greetable: function(greeting) { this.greet = `${greeting}, ${ this.valueOf() }!` } } function createGreetable(str) { const result = new String(str); Object.setPrototypeOf(result, greetablePrototype) return result; } const t = new createGreetable("world"); t.greetable("hello"); console.log(t.greet); console.log(t.length);

Producción:

 hello, [object String]! 5

Rendimiento esperado:

 hello, world! 5
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede extender la clase de cadena:

 class Greetable extends String { greet (greeting) { return `${greeting}, ${this}!`; } } const g = new Greetable('world'); g.greet('hello'); // hello, world! g.length // 5
about 4 years ago · Juan Pablo Isaza Report

0

Se necesitaron algunas modificaciones a su código para que funcione según lo previsto:

  1. Agregando this.length en la función prototipo greetable para actualizar la longitud de la cadena cada vez (recuerde que este es un objeto de cadena ).
  2. Cambiando la línea de const result a this.greet en la función constructora, configurando el prototipo de this en greetablePrototype según lo previsto, luego devolviendo la instancia de nuestro objeto return this .

 const greetablePrototype = { greetable: function(greeting) { this.greet = `${greeting}, ${this.greet}!` this.length = this.greet.length; } } function createGreetable(str) { this.greet = String(str); Object.setPrototypeOf(this, greetablePrototype) return this; } const t = new createGreetable("world"); t.greetable("hello"); console.log(t.greet); console.log(t.length);

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!