例如,我想在创建字符串时做点什么:
String = new Proxy(String, {
construct: (t, a) => {
return { a: 123 }
}
})
console.log(new String('q')) // { a: 123 }
但是,如果您使用基元,则不起作用。
String = new Proxy(String, {
construct: (t, a) => {
return { a: 123 }
}
})
console.log('1') // Expected: { a: 123 }, Actual: 1
有什么办法吗?
然后第二个问题是,当运行时转换基元时,可以代理该进程吗?
var a = '123' // This is a primitive
console.log('123'.substring(0,1)) // Actual: 1
// The runtime wraps the primitive as a String object.
// then uses a substring, and then returns the primitive.
现在:
String = new Proxy(String, {
construct: (t, a) => {
return { a: 123 }
},
apply: (target, object, args) => {
return { a: 123 }
}
})
console.log('1'.a) // Expected: 123 , Actual: undefined
我知道我可以在String的原型中添加'a'以达到期望。
但是我希望能够代理对图元的任意属性的访问。(是'1'.*
,不是jsut '1'.a
)
有什么办法吗?
谢谢您的回答。
不,这是不可能的。代理仅适用于对象,不适用于图元。不,您不能截获将原语转换为对象以访问其上的属性(包括方法)的内部(且经过优化的过程)。
涉及原语的某些操作确实使用了String.prototype
/Number.prototype
/ Boolean.prototype
上的方法,并且您敢于覆盖这些方法,但是您不能replace整个原型对象作为代理。 。