Is it possible to Proxy primitives (strings, numbers)?
Asked Answered
T

2

7

I'm exploring Proxies in JavaScript, and I want to know if there are any ways to Proxy primitives. If I try to do so:

new Proxy('I am a string');

It throws Uncaught TypeError: `target` argument of Proxy must be an object, got the string "I am a string"


The reason I want to do this is to be able to proxy the primitive's prototype methods. I could edit the prototype, but editing every single prototype function of every single primitive does not sound viable.

Trapezium answered 15/9, 2021 at 14:34 Comment(4)
As the message says, it expects an object, not a primitive. You could probably do new Proxy(new String("I am a string")). However, I suspect that might be an XY problem. What exactly do you want to do that requires proxying the methods?Pro
@Pro like I mentioned I'm just experimenting with the Proxy, and trying to learn more about it. There is no purpose.Trapezium
In that case, it seems that the error message contains all the information you wanted.Pro
@Pro definitely, I'm just looking for any hacks from the smart people over here :)Trapezium
S
12

You could work around it by wrapping the primitive value in an object:

const proxy = new Proxy({ value: 'I am a string' }, {
  get(target, prop, receiver) {
    const prim = Reflect.get(target, 'value');
    const value = prim[prop];
    return typeof value === 'function' ? value.bind(prim) : value;
  }
});

proxy.endsWith('ing');
// => true

proxy.valueOf();
// => 'I am a string'

'test ' + proxy;
// => 'test I am a string'

proxy[0];
// => 'I'
Sustentacular answered 15/9, 2021 at 14:43 Comment(0)
S
2

the chosen answer also works with bigints and symbols, but if you only want to support strings, numbers and booleans, you can just do

new Proxy(new String("I am a string"),handler);
new Proxy(new Number(5),handler);
new Proxy(new Boolean(true),handler);
Spray answered 22/4, 2023 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.