[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 to 6 (1+2+3).
  • On attempting to perform an addition operation like + 4, JavaScript internally looks for Symbol.toPrimitive to convert add 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.
posted @   Zhentiw  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示