Using JavaScript Proxies

shadowtime2000

shadowtime2000

Posted on September 30, 2020

Using JavaScript Proxies

In this post I will show you how to use a Proxy.

The concept of a proxy is pretty simple. You provide triggers that run when you are getting or setting something in an object.

// private user object
const _user = {
    name: "User",
    age: 25,
    _address: "A place"
}

const traps = {
    get(target, prop) {
        if (prop[0] === "_") {
            return undefined;
        }
    }
}

const user = new Proxy(_user, traps);

console.log(user.name) // User
console.log(user.age) // 25
console.log(user._address) // undefined
Enter fullscreen mode Exit fullscreen mode

As shown in the example above, Proxies can be used for stopping programs from accessing private variables.
They can also be used to stop programs from setting private variables.

// private user object
const _user = {
    name: "User",
    age: 25,
    _address: "A place"
}

const traps = {
    get(target, prop) {
        if (prop[0] === "_") {
            return undefined;
        }
    },
    set(target, prop, value) {
        if (prop[0] === "_") {
            return;
        } else {
            target[prop] = value;
        }
    }
}

const user = new Proxy(_user, traps);

user.name = "Person";
user.age = 26;

user._address = "In the world"; // Doesn't set
Enter fullscreen mode Exit fullscreen mode

You can read more about Proxies on the MDN.

💖 đŸ’Ș 🙅 đŸš©
shadowtime2000
shadowtime2000

Posted on September 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Objects in JavaScript
webdev Objects in JavaScript

September 19, 2024

Intro to DSA & Big O Notation
datastructures Intro to DSA & Big O Notation

September 19, 2024

Functions
javascript Functions

September 5, 2024

Array Loops in JavaScript
javascript Array Loops in JavaScript

July 20, 2024