如何代理 JavaScript 创建原语 [英] How to proxy JavaScript creation primitive

查看:34
本文介绍了如何代理 JavaScript 创建原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在创建字符串的时候做点什么,例如:

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

有什么办法吗?

那么第二个问题是,当运行时转换原语时,我可以代理进程吗?

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.

现在:

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' 来达到预期.

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

但我希望能够代理访问原语的任意属性.(是 '1'.*,不是 '1'.a)

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

有什么办法吗?

感谢您的回答.

推荐答案

不,这是不可能的.代理仅适用于对象,不适用于基元.不,您无法拦截将原语转换为对象以访问其上的属性(包括方法)的内部(和优化后)过程.

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.

一些涉及原语的操作确实使用了String.prototype/Number.prototype/Boolean.prototype 上的方法,你可以如果你敢,可以覆盖这些方法,但你不能替换代理的整个原型对象.

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.

这篇关于如何代理 JavaScript 创建原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆