How to proxy JavaScript creation primitive

江枫思渺然 提交于 2021-01-28 05:16:28

问题


I want to do something when creating a string, for example:

String = new Proxy(String, {
    construct: (t, a) => {
        return { a: 123 }
    }
})
console.log(new String('q')) // { a: 123 }

However, if you use primitives, it doesn't work.

String = new Proxy(String, {
    construct: (t, a) => {
        return { a: 123 }
    }
})
console.log('1') // Expected: { a: 123 }, Actual: 1

Is there any way?

then the second question is, when the runtime converts primitives, can I proxy the process?

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.

now:

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

I know I can add 'a' to the prototype of String to achieve the expectations.

But I want to be able to proxy access to arbitrary attributes for primitives. (Is '1'.*, Is not jsut '1'.a)

Is there any way?

Thank you for your answer.


回答1:


No, this is not possible. Proxies only work on objects, not on primitives. And no, you cannot intercept the internal (and optimised-away) process that converts a primitive to an object to access properties (including methods) on it.

Some of the operations involving primitives do use the methods on String.prototype / Number.prototype / Boolean.prototype, and you can overwrite these methods if you dare, but you cannot replace the entire prototype object for a proxy.



来源:https://stackoverflow.com/questions/60383942/how-to-proxy-javascript-creation-primitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!