Search code examples
javascriptnode.jsstringattributesgetter-setter

Define getter on a string


I know you cannot call Object.defineProperty on a string but I was wondering if there is a workarround to define getters on a string?

In other words, I'm looking for a workarround to be able to do something like this:

Object.defineProperty("Some string", "prop", {
    get: () => {
        return "Some other string";
    }
});

Maybe it's possible using symbol toPrimitive?

Note:
I know you can do "Some string".prop = "something" but that's not what I want, It's not the same as a getter


Solution

  • You can add a getter onto String.prototype, but that's your only option. String values are primitives; only objects can have properties. If you want a getter on a string, it must also appear on all strings. (Your getter could choose to do nothing if this != "some value", but that will of course apply to all strings that are "some value", not some particular string you've created.)

    Note also that "Some string".prop = "something" will throw when executed in strict mode code, which also includes class bodies, modules, and code explicitly marked as strict using "use strict"; at the start of the overall script or an enclosing function.