如何代理JavaScript创建原语

如何代理JavaScript创建原语

本文介绍了如何代理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'.* ,不是jsut '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创建原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:14