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

207
Visualizações
Add a method to a string variable's prototype

Expected: When a variable is created using createGreetable it should have an additional property greet set by greetable(text). The usual string methods should still be callable on this variable.

What I Tried:

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);

Output:

hello, [object String]!
5

Expected Output:

hello, world!
5
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can extend the string class:

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 Relatório

0

A few modifications to your code were needed to get it to work as intended:

  1. Adding this.length in the greetable prototype function to update the string length each time (remember this is a string object).
  2. Changing the const result line to this.greet in the constructor function, setting the prototype of this to the greetablePrototype as intended, then returning the instance of our object 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 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