Estoy explorando Proxies en JavaScript, y quiero saber si hay alguna forma de primitivas Proxy . Si trato de hacerlo:
new Proxy('I am a string'); Arroja Uncaught TypeError: `target` argument of Proxy must be an object, got the string "I am a string"
La razón por la que quiero hacer esto es poder representar los métodos prototipo de la primitiva. Podría editar el prototipo, pero editar cada función de prototipo de cada primitivo no parece viable.
Puede solucionarlo envolviendo el valor primitivo en un objeto:
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'