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.

4
  • 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. What exactly do you want to do that requires proxying the methods?
    – VLAZ
    Sep 15, 2021 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. Sep 15, 2021 at 14:40
  • 1
    In that case, it seems that the error message contains all the information you wanted.
    – VLAZ
    Sep 15, 2021 at 14:41
  • @VLAZ definitely, I'm just looking for any hacks from the smart people over here :) Sep 15, 2021 at 14:42

1 Answer 1

4

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.