javascriptprototype-chain

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

Solution

  • 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