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

3k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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'
0
On

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