是否可以代理原语(字符串,数字)?

问题描述 投票:0回答:2

我正在探索 JavaScript 中的代理,我想知道是否有任何方法可以实现

Proxy
原语。如果我尝试这样做:

new Proxy('I am a string');

它抛出

Uncaught TypeError: `target` argument of Proxy must be an object, got the string "I am a string"


我想这样做的原因是能够代理原语的原型方法。我可以编辑原型,但编辑每个原语的每个原型功能听起来不可行。

javascript primitive javascript-proxy
2个回答
4
投票

您可以通过将原始值包装在对象中来解决它:

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
投票

选择的答案也适用于 bigints 和符号,但如果你只想支持字符串、数字和布尔值,你可以这样做

new Proxy(new String("I am a string"),handler);
new Proxy(new Number(5),handler);
new Proxy(new Boolean(true),handler);
© www.soinside.com 2019 - 2024. All rights reserved.