in , ,

JavaScript Proxies

JavaScript Proxies
JavaScript Proxies

In this tutorial, you will find learn JavaScript proxies with the assistance of examples.

What is a Proxy?

JavaScript proxies can change the fundamental behavior of objects and functions. We can extend out the language to more readily suit our necessities or essentially use it for things like validation and access control on a property.

Until proxies were presented, we didn’t have native level access to change the fundamental behavior of an object, nor a function. Be that as it may, with them, we can go about as a center layer, to change how the object ought to be accessed, create data, for example, how many times a function has been called, and so forth

In JavaScript, proxies (proxy object) are used to wrap an object and redefine different tasks into the object, for example, reading, insertion, validation, and so on proxy allows you to add custom behavior to an object or a function.


Creating a Proxy Object

The syntax of proxy is:

new Proxy(target, handler);

Here,

  • new Proxy() – the constructor.
  • target – the object/function which you want to proxy
  • handler – can redefine the custom behavior of the object


For instance,

let student1 = {
    age: 24,
    name: "Sohail"
}

const handler = {
    get: function(obj, prop) {
        return obj[prop] ? obj[prop] : 'property does not exist';
    }
}

const proxy = new Proxy(student1, handler);
console.log(proxy.name); // Sohail
console.log(proxy.age); // 24
console.log(proxy.class); // property does not exist

Here, the get() technique is used to access the object’s property value. Furthermore, if the property isn’t accessible in the object, it returns a property that doesn’t exist.

As should be obvious, you can use a proxy to make new tasks for the object. A case may emerge when you need to check if an object has a specific key and play out an activity dependent on that key. In such cases, proxies can be used.

You can likewise pass an empty handler. At the point when an empty handler is passed, the proxy acts as a unique object. For instance,

let student = {
    name: 'Salman',
    age: 24
}

const handler = { };

// passing empty handler
const proxy1 = new Proxy(student, {});

console.log(proxy1); // Proxy {name: "Salman", age: 24}
console.log(proxy1.name); // Salman

Proxy handlers

Proxy provides two handler methods get() and set().

get() handler

The get() method is used to access the properties of a target object. For instance,

let student = {
    name: 'Salman',
    age: 24
}

const handler = {

    // get the object key and value
    get(obj, prop) {

        return obj[prop];
  }
}

const proxy = new Proxy(student, handler);
console.log(proxy.name); // Salman

Here, the get() method takes the object and the property as its parameters.


set() handler

The set() technique is used to set the value of an object. For instance,

let student = {
    name: 'Salman'
}

let setNewValue = {
  set: function(obj, prop, value) {

    obj[prop] = value;
    return;
  }
};

// setting new proxy
let person = new Proxy(student, setNewValue);

// setting new key/value
person.age = 25;
console.log(person); // Proxy {name: "Salman", age: 25}

Here, a new property age is added to the student object.


Uses of Proxy

1. For Validation

You can use a proxy for validation. You can check the value of a key and play out an activity-dependent on that value.

For instance,

let student = {
    name: 'Salman',
    age: 24
}

const handler = {

    // get the object key and value
    get(obj, prop) {

    // check condition
    if (prop == 'name') {
      return obj[prop];
    } else {
      return 'Not allowed';
    }
  }
}

const proxy = new Proxy(student, handler);
console.log(proxy.name); // Salman
console.log(proxy.age); // Not allowed

Here, just the name property of the student object is available. Else, it returns Not allowed.


2. Read the Only View of an Object

There might be times when you would prefer not to allow others to make changes to an object. In such cases, you can use a proxy to make an object readable only. For instance,

let student = {
    name: 'Salman',
    age: 23
}

const handler = {
    set: function (obj, prop, value) {
        if (obj[prop]) {
            
            // cannot change the student value
            console.log('Read only')
        }
    }
};

const proxy = new Proxy(student, handler);

proxy.name = 'Salman'; // Read only
proxy.age = 33; // Read only

In the above program, one can’t change the object in any capacity.

In the event that one attempts to transform the object in any capacity, you’ll just get a string saying Read Only.


3. Side Effects

You can use a proxy to call another function when a condition is met. For instance,

const myFunction = () => {
    console.log("execute this function")
};

const handler = {
    set: function (target, prop, value) {
        if (prop === 'name' && value === 'Salman') {
            // calling another function
            myFunction();
        }
        else {
            console.log('Can only access name property');
        }
    }
};

const proxy = new Proxy({}, handler);

proxy.name = 'Salman'; // execute this function
proxy.age = 33; // Can only access name property

JavaScript proxy was presented from the variant of JavaScript ES6. A few browsers may not completely support to use. To learn more, visit JavaScript proxy.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

JavaScript for… of Loop

JavaScript for… of Loop

Javascript setTimeout()

Javascript setTimeout()