DEV Community

loading...
Cover image for JavaScript Proxy

JavaScript Proxy

Damon Marc Rocha II
Hi, my name is Damon Rocha. I am a flatiron software engineering graduate. I have been coding for 4 years now.
・2 min read

I decided to take a break from the bash blogs I have been writing to cover something I recently discovered while traversing through the world of JavaScript, Proxies.

What Are Proxies

A JavaScript Proxy is an object that wraps around another object and intercepts/redefines any operation on it. So in other words, A proxy watches what happens to an object and conducts methods defined by the programmer. To create a proxy you need an object and a handler function. An example is shown below

Example:

const proxy1 = new Proxy(target, handler)

Enter fullscreen mode Exit fullscreen mode

The target is the object you are trying to control using the handler you define. A handler usually falls into four categories: lookup, assignment, enumeration, and function invocations. These functions can implement methods called traps. In this article, I will cover get() and set().

get() Example:

const user = {
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@example.com',
}

const handler = {
    get(target, property) {
        return property === 'fullName' ?
            `${target.firstName} ${target.lastName}` :
            target[property];
    }
};

let proxy = new Proxy(target, handler);
console.log(proxy.fullName) //=> John Doe
Enter fullscreen mode Exit fullscreen mode

The get trap is called when an object is accessed via the proxy item. It takes in the object and property that is being called and then returns various types of information; even that which was not originally stored in the object (e.g fullName).

set() Example:

The set trap controls behavior on the object when a property is changed.

const triangle = {
    base: 100,
    height: 50,
}

const handler = {
    get: function (target, property){
        if(property === 'area'){
           return 0.5*target.base*target.height
        }
        return target[property]
    },
    set: function (target, property, value) {
            if (typeof value !== 'number') {
                throw new Error(`${property} must be a number.`);
            }
            if (value < 0) {
                throw new Error(`The ${property} must be 18 or older.`)
            }
        }
        target[property] = value;
    }
};

const proxyUser = new Proxy(triangle, handler);
Enter fullscreen mode Exit fullscreen mode

Other Traps

  • apply()
  • construct
  • getPrototypeOf
  • setPrototypeOf
  • isExtensible
  • preventExtensions
  • getOwnPropertyDescriptor

Now I know a lot of this can be created via classes now, but I know there are some places where a lightweight customizable Proxy would be a great option. If you agree with this then here is another resource.
Thanks for reading and it's back to bash next week. See you then.

Discussion (1)

Collapse
bretgeek profile image
bretgeek

Great read! YumJS uses proxies for it's Reactors to make any element reactive:) Check out my YumJS article here dev.to/bretgeek/introducing-yumjs-... (the part about the Reactors) and have a look at the code github.com/bretgeek/yumjs (if you are interested of course).