3

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
    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](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What exactly do you want to do that requires proxying the methods? – VLAZ Sep 15 '21 at 14:37
  • @VLAZ like I mentioned I'm just experimenting with the Proxy, and trying to learn more about it. There is no purpose. – Siddharth Shyniben Sep 15 '21 at 14:40
  • 1
    In that case, it seems that the error message contains all the information you wanted. – VLAZ Sep 15 '21 at 14:41
  • @VLAZ definitely, I'm just looking for any hacks from the smart people over here :) – Siddharth Shyniben Sep 15 '21 at 14:42

2 Answers2

5

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'
Andrew Dibble
  • 782
  • 6
  • 15
0

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