[Javascript] Understanding JavaScript Proxies with Symbol.toPrimitive
In this post, we’ll explore an intriguing use of JavaScript’s Proxy
and Symbol.toPrimitive
to perform cumulative operations, mimicking a numeric context.
The Setup
We define a Proxy
to intercept property accesses and arithmetic operations:
const add = new Proxy({
_store: 0
}, {
get: function(target, key, receiver) {
if (key === Symbol.toPrimitive) {
// Returns a function that retrieves the _store value
return () => target._store;
}
target._store += +key; // Convert key to number and add to _store
return receiver; // Return the proxy to allow chaining
}
});
Key Components
- Proxy: A special object that lets you redefine fundamental operations (like property lookup, assignment, and others).
- _store: A property to keep the cumulative sum.
- get trap: A function that runs when property access is attempted on the proxy.
- Symbol.toPrimitive: A built-in symbol used as a key to define a function converting an object to a primitive value. Here, it ensures the proxy behaves like a numeric value when used in arithmetic operations.
How It Works
When properties (which are numbers in this context) are accessed on the add
proxy, we convert them to numbers and add them to _store
. Using chaining, we can accumulate values:
add[1][2][3]
sets_store
to6
(1+2+3).- On attempting to perform an addition operation like
+ 4
, JavaScript internally looks forSymbol.toPrimitive
to convertadd
to a number, triggering the return of_store
(6), which is then used in the arithmetic operation.
Examples
const res1 = add[1][2][3] + 4; // 10
const res2 = add[10][20][30] + 40; // 100
const res3 = add[100][200][300] + 400; // 1000
Each line showcases the ability to chain accesses that cumulatively add up, demonstrating the power of
Proxy
and Symbol.toPrimitive
in creating flexible, functional behaviors in JavaScript applications.
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-08-28 [React Typescript] Strongly type Render prop
2023-08-28 [React Typescript] Strongly Typing Lazy Loaded Components with Generics
2020-08-28 [Postgres] Keep Data Integrity with Constraints
2020-08-28 [Postgres] Removing Data with SQL Delete, Truncate, and Drop
2020-08-28 [Postgres] Using uuid-ossp extenstion
2020-08-28 [Machine Learning] Simplified Cost Function and Gradient Descent
2019-08-28 [SCSS] SASS dynamic class properties