javascriptprimitivees6-proxy

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


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.


Solution

  • 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'