Home > Enterprise >  Attach a method to a primitive
Attach a method to a primitive

Time:01-15

I was wondering if it's possible to attach a method to a primitive (e.g., a string) while still being able to use it as the primitive. Note: this is different from adding methods to the String class as described in other questions (e.g., Extend a String class in ES6).

For instance, here's some dummy code of what I've been trying. Essentially, I could wrap the primitive in a class, add methods to that class, the somehow still be able to access the underlying value automatically?

class MyString {
    value: string

    constructor(value) {
        this.value = value
    }

    get5thCharacter() {
        return this.value[4]
    }
}

const hello = new MyString("hello")
const world = "world"

// desired results
console.log(hello   " "   world) // "hello world"
console.log(hello.get5thCharacter()) // "o"
console.log(world.get5thCharacter()) // TypeError: world.get5thCharacter is not a function

Notice also that while world is also a String, world does not have the method I defined on hello, despite the fact they can both otherwise be used as strings.

Any thoughts?

CodePudding user response:

After playing aroudn with Konrad's answer, I think I found the solution. By extending the primitive type it still acts like that primitive. You can also still access methods and properties of the original.

class MyString extends String {
  constructor(value) {
super(value);
this.value = value;
  }

  get5thCharacter() {
return this.value[4];
  }
}

const hello = new MyString("hello");
const world = "world";

console.log(hello   " "   world); // "hello world"
console.log(hello.length);
console.log(world.length);
console.log(hello.get5thCharacter()); // "o"
console.log(world.get5thCharacter()); // TypeError: world.get5thCharacter is not a function

CodePudding user response:

class MyString {
  constructor(value) {
    this.value = value
  }

  get5thCharacter() {
    return this.value[4]
  }

  toString() {
    return this.value
  }
}

const hello = new MyString("hello")
const world = "world"

console.log(hello   " "   world) // "hello world"
console.log(hello.get5thCharacter()) // "o"
console.log(world.get5thCharacter()) // TypeError: world.get5thCharacter is not a function

  • Related