[Javascript] Understanding JavaScript Proxies with Symbol.toPrimitive

Zhentiw發表於2024-08-28

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.

相關文章