Jump to content

Featured Replies

Posted

You are reading Part 35 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]

Introduction

JavaScript's Proxy and Reflect APIs provide powerful tools for intercepting and customizing fundamental operations on objects. The Proxy API allows developers to define custom behaviors for property access, function calls, and more. The Reflect API complements Proxies by standardizing built-in object operations.

1. Understanding JavaScript Proxies

A Proxy acts as an intermediary between an object and the operations performed on it. It allows developers to define custom behavior when interacting with the object.

Syntax:

let proxy = new Proxy(target, handler);
  • target: The original object being proxied.

  • handler: An object containing traps that define how operations on the proxy should be intercepted.

Example: Basic Proxy Usage

let user = { name: "Alice" };

let proxyUser = new Proxy(user, {
    get(target, property) {
        console.log(`Accessing ${property}`);
        return target[property];
    }
});

console.log(proxyUser.name); // Logs: "Accessing name", then "Alice"

2. Proxy Traps: Intercepting Object Operations

Proxies use traps to define custom behaviors for fundamental object operations.

Common Proxy Traps:

Trap

Description

get(target, prop, receiver)

Intercepts property access.

set(target, prop, value, receiver)

Intercepts property assignment.

deleteProperty(target, prop)

Intercepts property deletion.

has(target, prop)

Intercepts in operator usage.

apply(target, thisArg, args)

Intercepts function calls.

construct(target, args, newTarget)

Intercepts object instantiation with new.

Example: Validating Property Assignment

let validator = {
    age: 25
};

let proxyValidator = new Proxy(validator, {
    set(target, prop, value) {
        if (prop === "age" && value < 0) {
            throw new Error("Age cannot be negative");
        }
        target[prop] = value;
        return true;
    }
});

proxyValidator.age = 30; // Valid
// proxyValidator.age = -5; // Throws error

3. Using Reflect API

The Reflect API provides utility functions that mirror object operations and simplify proxy handling.

Example: Using Reflect for a Proxy

let person = { name: "John", age: 25 };

let proxyPerson = new Proxy(person, {
    get(target, prop) {
        console.log(`Getting property: ${prop}`);
        return Reflect.get(target, prop);
    },
    set(target, prop, value) {
        console.log(`Setting ${prop} to ${value}`);
        return Reflect.set(target, prop, value);
    }
});

console.log(proxyPerson.name); // Logs: "Getting property: name", then "John"
proxyPerson.age = 30; // Logs: "Setting age to 30"

Why Use Reflect?

  • Provides default behavior for intercepted operations.

  • Ensures consistent, error-free handling of object operations.

  • Simplifies debugging by logging operations explicitly.

4. Practical Use Cases of Proxies

1. Data Validation

let userInput = new Proxy({}, {
    set(target, prop, value) {
        if (typeof value !== "string") {
            throw new Error("Only strings are allowed");
        }
        target[prop] = value;
        return true;
    }
});

userInput.username = "Alice"; // Works
// userInput.age = 30; // Throws error

2. Auto-tracking Property Access

let logAccess = new Proxy({}, {
    get(target, prop) {
        console.log(`Property accessed: ${prop}`);
        return Reflect.get(target, prop);
    }
});

console.log(logAccess.test); // Logs: "Property accessed: test"

3. Default Fallback Values

let defaults = new Proxy({}, {
    get(target, prop) {
        return prop in target ? target[prop] : "Default Value";
    }
});

console.log(defaults.name); // Output: "Default Value"

5. When to Use Proxies & Reflect API

Use Case

Best Choice

Logging property access

Proxy with get trap

Data validation

Proxy with set trap

Applying default values

Proxy with fallback logic

Enhancing built-in object behavior

Reflect API

You are reading Part 35 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]

  • Views 27
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.